/*!
 * jQuery corner plugin: simple corner rounding
 * Examples and documentation at: http://jquery.malsup.com/corner/
 * version 2.01 (08-SEP-2009)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */

/**
 *  corner() takes a single string argument:  $('#myDiv').corner("effect corners width")
 *
 *  effect:  name of the effect to apply, such as round, bevel, notch, bite, etc (default is round). 
 *  corners: one or more of: top, bottom, tr, tl, br, or bl. 
 *           by default, all four corners are adorned. 
 *  width:   width of the effect; in the case of rounded corners this is the radius. 
 *           specify this value using the px suffix such as 10px (and yes, it must be pixels).
 *
 * @author Dave Methvin (http://methvin.com/jquery/jq-corner.html)
 * @author Mike Alsup   (http://jquery.malsup.com/corner/)
 */
;(function($) { 

var moz = $.browser.mozilla && /gecko/i.test(navigator.userAgent);
var webkit = $.browser.safari && $.browser.version >= 3;

var expr = $.browser.msie && (function() {
    var div = document.createElement('div');
    try { div.style.setExpression('width','0+0'); }
    catch(e) { return false; }
    return true;
})();
    
function sz(el, p) { 
    return parseInt($.css(el,p))||0; 
};
function hex2(s) {
    var s = parseInt(s).toString(16);
    return ( s.length < 2 ) ? '0'+s : s;
};
function gpc(node) {
    for ( ; node && node.nodeName.toLowerCase() != 'html'; node = node.parentNode ) {
        var v = $.css(node,'backgroundColor');
        if (v == 'rgba(0, 0, 0, 0)')
            continue; // webkit
        if (v.indexOf('rgb') >= 0) { 
            var rgb = v.match(/\d+/g); 
            return '#'+ hex2(rgb[0]) + hex2(rgb[1]) + hex2(rgb[2]);
        }
        if ( v && v != 'transparent' )
            return v;
    }
    return '#ffffff';
};

function getWidth(fx, i, width) {
    switch(fx) {
    case 'round':  return Math.round(width*(1-Math.cos(Math.asin(i/width))));
    case 'cool':   return Math.round(width*(1+Math.cos(Math.asin(i/width))));
    case 'sharp':  return Math.round(width*(1-Math.cos(Math.acos(i/width))));
    case 'bite':   return Math.round(width*(Math.cos(Math.asin((width-i-1)/width))));
    case 'slide':  return Math.round(width*(Math.atan2(i,width/i)));
    case 'jut':    return Math.round(width*(Math.atan2(width,(width-i-1))));
    case 'curl':   return Math.round(width*(Math.atan(i)));
    case 'tear':   return Math.round(width*(Math.cos(i)));
    case 'wicked': return Math.round(width*(Math.tan(i)));
    case 'long':   return Math.round(width*(Math.sqrt(i)));
    case 'sculpt': return Math.round(width*(Math.log((width-i-1),width)));
    case 'dog':    return (i&1) ? (i+1) : width;
    case 'dog2':   return (i&2) ? (i+1) : width;
    case 'dog3':   return (i&3) ? (i+1) : width;
    case 'fray':   return (i%2)*width;
    case 'notch':  return width; 
    case 'bevel':  return i+1;
    }
};

$.fn.corner = function(options) {
    // in 1.3+ we can fix mistakes with the ready state
	if (this.length == 0) {
        if (!$.isReady && this.selector) {
            var s = this.selector, c = this.context;
            $(function() {
                $(s,c).corner(options);
            });
        }
        return this;
	}

    return this.each(function(index){
		var $this = $(this);
		var o = (options || $this.attr($.fn.corner.defaults.metaAttr) || '').toLowerCase();
		var keep = /keep/.test(o);                       // keep borders?
		var cc = ((o.match(/cc:(#[0-9a-f]+)/)||[])[1]);  // corner color
		var sc = ((o.match(/sc:(#[0-9a-f]+)/)||[])[1]);  // strip color
		var width = parseInt((o.match(/(\d+)px/)||[])[1]) || 10; // corner width
		var re = /round|bevel|notch|bite|cool|sharp|slide|jut|curl|tear|fray|wicked|sculpt|long|dog3|dog2|dog/;
		var fx = ((o.match(re)||['round'])[0]);
		var edges = { T:0, B:1 };
		var opts = {
			TL:  /top|tl|left/.test(o),       TR:  /top|tr|right/.test(o),
			BL:  /bottom|bl|left/.test(o),    BR:  /bottom|br|right/.test(o)
		};
		if ( !opts.TL && !opts.TR && !opts.BL && !opts.BR )
			opts = { TL:1, TR:1, BL:1, BR:1 };
			
		// support native rounding
		if ($.fn.corner.defaults.useNative && fx == 'round' && (moz || webkit) && !cc && !sc) {
			if (opts.TL)
				$this.css(moz ? '-moz-border-radius-topleft' : '-webkit-border-top-left-radius', width + 'px');
			if (opts.TR)
				$this.css(moz ? '-moz-border-radius-topright' : '-webkit-border-top-right-radius', width + 'px');
			if (opts.BL)
				$this.css(moz ? '-moz-border-radius-bottomleft' : '-webkit-border-bottom-left-radius', width + 'px');
			if (opts.BR)
				$this.css(moz ? '-moz-border-radius-bottomright' : '-webkit-border-bottom-right-radius', width + 'px');
			return;
		}
			
		var strip = document.createElement('div');
		strip.style.overflow = 'hidden';
		strip.style.height = '1px';
		strip.style.backgroundColor = sc || 'transparent';
		strip.style.borderStyle = 'solid';
	
        var pad = {
            T: parseInt($.css(this,'paddingTop'))||0,     R: parseInt($.css(this,'paddingRight'))||0,
            B: parseInt($.css(this,'paddingBottom'))||0,  L: parseInt($.css(this,'paddingLeft'))||0
        };

        if (typeof this.style.zoom != undefined) this.style.zoom = 1; // force 'hasLayout' in IE
        if (!keep) this.style.border = 'none';
        strip.style.borderColor = cc || gpc(this.parentNode);
        var cssHeight = $.curCSS(this, 'height');

        for (var j in edges) {
            var bot = edges[j];
            // only add stips if needed
            if ((bot && (opts.BL || opts.BR)) || (!bot && (opts.TL || opts.TR))) {
                strip.style.borderStyle = 'none '+(opts[j+'R']?'solid':'none')+' none '+(opts[j+'L']?'solid':'none');
                var d = document.createElement('div');
                $(d).addClass('jquery-corner');
                var ds = d.style;

                bot ? this.appendChild(d) : this.insertBefore(d, this.firstChild);

                if (bot && cssHeight != 'auto') {
                    if ($.css(this,'position') == 'static')
                        this.style.position = 'relative';
                    ds.position = 'absolute';
                    ds.bottom = ds.left = ds.padding = ds.margin = '0';
                    if (expr)
                        ds.setExpression('width', 'this.parentNode.offsetWidth');
                    else
                        ds.width = '100%';
                }
                else if (!bot && $.browser.msie) {
                    if ($.css(this,'position') == 'static')
                        this.style.position = 'relative';
                    ds.position = 'absolute';
                    ds.top = ds.left = ds.right = ds.padding = ds.margin = '0';
                    
                    // fix ie6 problem when blocked element has a border width
                    if (expr) {
                        var bw = sz(this,'borderLeftWidth') + sz(this,'borderRightWidth');
                        ds.setExpression('width', 'this.parentNode.offsetWidth - '+bw+'+ "px"');
                    }
                    else
                        ds.width = '100%';
                }
                else {
                	ds.position = 'relative';
                    ds.margin = !bot ? '-'+pad.T+'px -'+pad.R+'px '+(pad.T-width)+'px -'+pad.L+'px' : 
                                        (pad.B-width)+'px -'+pad.R+'px -'+pad.B+'px -'+pad.L+'px';                
                }

                for (var i=0; i < width; i++) {
                    var w = Math.max(0,getWidth(fx,i, width));
                    var e = strip.cloneNode(false);
                    e.style.borderWidth = '0 '+(opts[j+'R']?w:0)+'px 0 '+(opts[j+'L']?w:0)+'px';
                    bot ? d.appendChild(e) : d.insertBefore(e, d.firstChild);
                }
            }
        }
    });
};

$.fn.uncorner = function() { 
	if (moz || webkit)
		this.css(moz ? '-moz-border-radius' : '-webkit-border-radius', 0);
	$('div.jquery-corner', this).remove();
	return this;
};

// expose options
$.fn.corner.defaults = {
	useNative: true, // true if plugin should attempt to use native browser support for border radius rounding
	metaAttr:  'data-corner' // name of meta attribute to use for options
};
    
})(jQuery);
//RCorner End//


//INPUT Fonk Begin
	var map=new Array();
	$.Watermark = {
		ShowAll:function(){
			for (var i=0;i<map.length;i++){
				if(map[i].obj.val()==""){
					map[i].obj.val(map[i].text);					
					map[i].obj.css("color",map[i].WatermarkColor);
				}else{
				    map[i].obj.css("color",map[i].DefaultColor);
				}
			}
		},
		HideAll:function(){
			for (var i=0;i<map.length;i++){
				if(map[i].obj.val()==map[i].text)
					map[i].obj.val("");					
			}
		}
	};
	
	$.fn.Watermark = function(text,color) {
		if(!color)
			color="#666666";
		return this.each(
			function(){		
				var input=$(this);
				var defaultColor=input.css("color");
				map[map.length]={text:text,obj:input,DefaultColor:defaultColor,WatermarkColor:color};
				function clearMessage(){
					if(input.val()==text)
						input.val("");
					input.css("color",defaultColor);
				}

				function insertMessage(){
					if(input.val().length==0 || input.val()==text){
						input.val(text);
						input.css("color",color);	
					}else
						input.css("color",defaultColor);				
				}

				input.focus(clearMessage);
				input.blur(insertMessage);								
				input.change(insertMessage);
				
				insertMessage();
			}
		);
	}

//INPUT Fonk End

//form plugin

/*
 * jQuery Form Plugin
 * version: 2.36 (07-NOV-2009)
 * @requires jQuery v1.2.6 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
;(function($) {

/*
	Usage Note:
	-----------
	Do not use both ajaxSubmit and ajaxForm on the same form.  These
	functions are intended to be exclusive.  Use ajaxSubmit if you want
	to bind your own submit handler to the form.  For example,

	$(document).ready(function() {
		$('#myForm').bind('submit', function() {
			$(this).ajaxSubmit({
				target: '#output'
			});
			return false; // <-- important!
		});
	});

	Use ajaxForm when you want the plugin to manage all the event binding
	for you.  For example,

	$(document).ready(function() {
		$('#myForm').ajaxForm({
			target: '#output'
		});
	});

	When using ajaxForm, the ajaxSubmit function will be invoked for you
	at the appropriate time.
*/

/**
 * ajaxSubmit() provides a mechanism for immediately submitting
 * an HTML form using AJAX.
 */
$.fn.ajaxSubmit = function(options) {
	// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
	if (!this.length) {
		log('ajaxSubmit: skipping submit process - no element selected');
		return this;
	}

	if (typeof options == 'function')
		options = { success: options };

	var url = $.trim(this.attr('action'));
	if (url) {
		// clean url (don't include hash vaue)
		url = (url.match(/^([^#]+)/)||[])[1];
   	}
   	url = url || window.location.href || '';

	options = $.extend({
		url:  url,
		type: this.attr('method') || 'GET',
		iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
	}, options || {});

	// hook for manipulating the form data before it is extracted;
	// convenient for use with rich editors like tinyMCE or FCKEditor
	var veto = {};
	this.trigger('form-pre-serialize', [this, options, veto]);
	if (veto.veto) {
		log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
		return this;
	}

	// provide opportunity to alter form data before it is serialized
	if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
		log('ajaxSubmit: submit aborted via beforeSerialize callback');
		return this;
	}

	var a = this.formToArray(options.semantic);
	if (options.data) {
		options.extraData = options.data;
		for (var n in options.data) {
		  if(options.data[n] instanceof Array) {
			for (var k in options.data[n])
			  a.push( { name: n, value: options.data[n][k] } );
		  }
		  else
			 a.push( { name: n, value: options.data[n] } );
		}
	}

	// give pre-submit callback an opportunity to abort the submit
	if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
		log('ajaxSubmit: submit aborted via beforeSubmit callback');
		return this;
	}

	// fire vetoable 'validate' event
	this.trigger('form-submit-validate', [a, this, options, veto]);
	if (veto.veto) {
		log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
		return this;
	}

	var q = $.param(a);

	if (options.type.toUpperCase() == 'GET') {
		options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
		options.data = null;  // data is null for 'get'
	}
	else
		options.data = q; // data is the query string for 'post'

	var $form = this, callbacks = [];
	if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
	if (options.clearForm) callbacks.push(function() { $form.clearForm(); });

	// perform a load on the target only if dataType is not provided
	if (!options.dataType && options.target) {
		var oldSuccess = options.success || function(){};
		callbacks.push(function(data) {
			$(options.target).html(data).each(oldSuccess, arguments);
		});
	}
	else if (options.success)
		callbacks.push(options.success);

	options.success = function(data, status) {
		for (var i=0, max=callbacks.length; i < max; i++)
			callbacks[i].apply(options, [data, status, $form]);
	};

	// are there files to upload?
	var files = $('input:file', this).fieldValue();
	var found = false;
	for (var j=0; j < files.length; j++)
		if (files[j])
			found = true;

	var multipart = false;
//	var mp = 'multipart/form-data';
//	multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);

	// options.iframe allows user to force iframe mode
	// 06-NOV-09: now defaulting to iframe mode if file input is detected
   if ((files.length && options.iframe !== false) || options.iframe || found || multipart) {
	   // hack to fix Safari hang (thanks to Tim Molendijk for this)
	   // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
	   if (options.closeKeepAlive)
		   $.get(options.closeKeepAlive, fileUpload);
	   else
		   fileUpload();
	   }
   else
	   $.ajax(options);

	// fire 'notify' event
	this.trigger('form-submit-notify', [this, options]);
	return this;


	// private function for handling file uploads (hat tip to YAHOO!)
	function fileUpload() {
		var form = $form[0];

		if ($(':input[name=submit]', form).length) {
			alert('Error: Form elements must not be named "submit".');
			return;
		}

		var opts = $.extend({}, $.ajaxSettings, options);
		var s = $.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);

		var id = 'jqFormIO' + (new Date().getTime());
		var $io = $('<iframe id="' + id + '" name="' + id + '" src="'+ opts.iframeSrc +'" />');
		var io = $io[0];

		$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

		var xhr = { // mock object
			aborted: 0,
			responseText: null,
			responseXML: null,
			status: 0,
			statusText: 'n/a',
			getAllResponseHeaders: function() {},
			getResponseHeader: function() {},
			setRequestHeader: function() {},
			abort: function() {
				this.aborted = 1;
				$io.attr('src', opts.iframeSrc); // abort op in progress
			}
		};

		var g = opts.global;
		// trigger ajax global events so that activity/block indicators work like normal
		if (g && ! $.active++) $.event.trigger("ajaxStart");
		if (g) $.event.trigger("ajaxSend", [xhr, opts]);

		if (s.beforeSend && s.beforeSend(xhr, s) === false) {
			s.global && $.active--;
			return;
		}
		if (xhr.aborted)
			return;

		var cbInvoked = 0;
		var timedOut = 0;

		// add submitting element to data if we know it
		var sub = form.clk;
		if (sub) {
			var n = sub.name;
			if (n && !sub.disabled) {
				options.extraData = options.extraData || {};
				options.extraData[n] = sub.value;
				if (sub.type == "image") {
					options.extraData[name+'.x'] = form.clk_x;
					options.extraData[name+'.y'] = form.clk_y;
				}
			}
		}

		// take a breath so that pending repaints get some cpu time before the upload starts
		setTimeout(function() {
			// make sure form attrs are set
			var t = $form.attr('target'), a = $form.attr('action');

			// update form attrs in IE friendly way
			form.setAttribute('target',id);
			if (form.getAttribute('method') != 'POST')
				form.setAttribute('method', 'POST');
			if (form.getAttribute('action') != opts.url)
				form.setAttribute('action', opts.url);

			// ie borks in some cases when setting encoding
			if (! options.skipEncodingOverride) {
				$form.attr({
					encoding: 'multipart/form-data',
					enctype:  'multipart/form-data'
				});
			}

			// support timout
			if (opts.timeout)
				setTimeout(function() { timedOut = true; cb(); }, opts.timeout);

			// add "extra" data to form if provided in options
			var extraInputs = [];
			try {
				if (options.extraData)
					for (var n in options.extraData)
						extraInputs.push(
							$('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
								.appendTo(form)[0]);

				// add iframe to doc and submit the form
				$io.appendTo('body');
				io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
				form.submit();
			}
			finally {
				// reset attrs and remove "extra" input elements
				form.setAttribute('action',a);
				t ? form.setAttribute('target', t) : $form.removeAttr('target');
				$(extraInputs).remove();
			}
		}, 10);

		var domCheckCount = 50;

		function cb() {
			if (cbInvoked++) return;

			io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);

			var ok = true;
			try {
				if (timedOut) throw 'timeout';
				// extract the server response from the iframe
				var data, doc;

				doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
				
				var isXml = opts.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
				log('isXml='+isXml);
				if (!isXml && (doc.body == null || doc.body.innerHTML == '')) {
				 	if (--domCheckCount) {
						// in some browsers (Opera) the iframe DOM is not always traversable when
						// the onload callback fires, so we loop a bit to accommodate
						cbInvoked = 0;
						setTimeout(cb, 100);
						return;
					}
					log('Could not access iframe DOM after 50 tries.');
					return;
				}

				xhr.responseText = doc.body ? doc.body.innerHTML : null;
				xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
				xhr.getResponseHeader = function(header){
					var headers = {'content-type': opts.dataType};
					return headers[header];
				};

				if (opts.dataType == 'json' || opts.dataType == 'script') {
					// see if user embedded response in textarea
					var ta = doc.getElementsByTagName('textarea')[0];
					if (ta)
						xhr.responseText = ta.value;
					else {
						// account for browsers injecting pre around json response
						var pre = doc.getElementsByTagName('pre')[0];
						if (pre)
							xhr.responseText = pre.innerHTML;
					}			  
				}
				else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
					xhr.responseXML = toXml(xhr.responseText);
				}
				data = $.httpData(xhr, opts.dataType);
			}
			catch(e){
				ok = false;
				$.handleError(opts, xhr, 'error', e);
			}

			// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
			if (ok) {
				opts.success(data, 'success');
				if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
			}
			if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
			if (g && ! --$.active) $.event.trigger("ajaxStop");
			if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');

			// clean up
			setTimeout(function() {
				$io.remove();
				xhr.responseXML = null;
			}, 100);
		};

		function toXml(s, doc) {
			if (window.ActiveXObject) {
				doc = new ActiveXObject('Microsoft.XMLDOM');
				doc.async = 'false';
				doc.loadXML(s);
			}
			else
				doc = (new DOMParser()).parseFromString(s, 'text/xml');
			return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
		};
	};
};

/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *	is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *	used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.
 */
$.fn.ajaxForm = function(options) {
	return this.ajaxFormUnbind().bind('submit.form-plugin', function() {
		$(this).ajaxSubmit(options);
		return false;
	}).bind('click.form-plugin', function(e) {
		var target = e.target;
		var $el = $(target);
		if (!($el.is(":submit,input:image"))) {
			// is this a child element of the submit el?  (ex: a span within a button)
			var t = $el.closest(':submit');
			if (t.length == 0)
				return;
			target = t[0];
		}
		var form = this;
		form.clk = target;
		if (target.type == 'image') {
			if (e.offsetX != undefined) {
				form.clk_x = e.offsetX;
				form.clk_y = e.offsetY;
			} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
				var offset = $el.offset();
				form.clk_x = e.pageX - offset.left;
				form.clk_y = e.pageY - offset.top;
			} else {
				form.clk_x = e.pageX - target.offsetLeft;
				form.clk_y = e.pageY - target.offsetTop;
			}
		}
		// clear form vars
		setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
	});
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
	return this.unbind('submit.form-plugin click.form-plugin');
};

/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
$.fn.formToArray = function(semantic) {
	var a = [];
	if (this.length == 0) return a;

	var form = this[0];
	var els = semantic ? form.getElementsByTagName('*') : form.elements;
	if (!els) return a;
	for(var i=0, max=els.length; i < max; i++) {
		var el = els[i];
		var n = el.name;
		if (!n) continue;

		if (semantic && form.clk && el.type == "image") {
			// handle image inputs on the fly when semantic == true
			if(!el.disabled && form.clk == el) {
				a.push({name: n, value: $(el).val()});
				a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
			}
			continue;
		}

		var v = $.fieldValue(el, true);
		if (v && v.constructor == Array) {
			for(var j=0, jmax=v.length; j < jmax; j++)
				a.push({name: n, value: v[j]});
		}
		else if (v !== null && typeof v != 'undefined')
			a.push({name: n, value: v});
	}

	if (!semantic && form.clk) {
		// input type=='image' are not found in elements array! handle it here
		var $input = $(form.clk), input = $input[0], n = input.name;
		if (n && !input.disabled && input.type == 'image') {
			a.push({name: n, value: $input.val()});
			a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
		}
	}
	return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
	//hand off to jQuery.param for proper encoding
	return $.param(this.formToArray(semantic));
};

/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
	var a = [];
	this.each(function() {
		var n = this.name;
		if (!n) return;
		var v = $.fieldValue(this, successful);
		if (v && v.constructor == Array) {
			for (var i=0,max=v.length; i < max; i++)
				a.push({name: n, value: v[i]});
		}
		else if (v !== null && typeof v != 'undefined')
			a.push({name: this.name, value: v});
	});
	//hand off to jQuery.param for proper encoding
	return $.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *	  <input name="A" type="text" />
 *	  <input name="A" type="text" />
 *	  <input name="B" type="checkbox" value="B1" />
 *	  <input name="B" type="checkbox" value="B2"/>
 *	  <input name="C" type="radio" value="C1" />
 *	  <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *	   array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
	for (var val=[], i=0, max=this.length; i < max; i++) {
		var el = this[i];
		var v = $.fieldValue(el, successful);
		if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
			continue;
		v.constructor == Array ? $.merge(val, v) : val.push(v);
	}
	return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
	var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
	if (typeof successful == 'undefined') successful = true;

	if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
		(t == 'checkbox' || t == 'radio') && !el.checked ||
		(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
		tag == 'select' && el.selectedIndex == -1))
			return null;

	if (tag == 'select') {
		var index = el.selectedIndex;
		if (index < 0) return null;
		var a = [], ops = el.options;
		var one = (t == 'select-one');
		var max = (one ? index+1 : ops.length);
		for(var i=(one ? index : 0); i < max; i++) {
			var op = ops[i];
			if (op.selected) {
				var v = op.value;
				if (!v) // extra pain for IE...
					v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
				if (one) return v;
				a.push(v);
			}
		}
		return a;
	}
	return el.value;
};

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function() {
	return this.each(function() {
		$('input,select,textarea', this).clearFields();
	});
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
	return this.each(function() {
		var t = this.type, tag = this.tagName.toLowerCase();
		if (t == 'text' || t == 'password' || tag == 'textarea')
			this.value = '';
		else if (t == 'checkbox' || t == 'radio')
			this.checked = false;
		else if (tag == 'select')
			this.selectedIndex = -1;
	});
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
	return this.each(function() {
		// guard against an input with the name of 'reset'
		// note that IE reports the reset function as an 'object'
		if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
			this.reset();
	});
};

/**
 * Enables or disables any matching elements.
 */
$.fn.enable = function(b) {
	if (b == undefined) b = true;
	return this.each(function() {
		this.disabled = !b;
	});
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
$.fn.selected = function(select) {
	if (select == undefined) select = true;
	return this.each(function() {
		var t = this.type;
		if (t == 'checkbox' || t == 'radio')
			this.checked = select;
		else if (this.tagName.toLowerCase() == 'option') {
			var $sel = $(this).parent('select');
			if (select && $sel[0] && $sel[0].type == 'select-one') {
				// deselect all other options
				$sel.find('option').selected(false);
			}
			this.selected = select;
		}
	});
};

// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
	if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
		window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};

})(jQuery);
//form plugin end

var caretPositionAmp = new Array();
function init() {
    if(navigator.appName == "Microsoft Internet Explorer") {
        obj = document.getElementsByTagName('TEXTAREA');
        var input;
        var i = 0;
        for (var i = 0; i < obj.length; i++) {
            input = obj[i];
            caretPositionAmp[i] = input.value.length;
            input.onmouseup = function() { // for IE because it loses caret position when focus changed
                input = document.activeElement;
                for (var i = 0; i < obj.length; i++) {
                    if (obj[i] == input) {
                        break;
                    }
                }
                input.focus();
                var s = document.selection.createRange();
                var re = input.createTextRange();
                var rc = re.duplicate();
                re.moveToBookmark(s.getBookmark());
                rc.setEndPoint("EndToStart", re);
                caretPositionAmp[i] = rc.text.length;
            }
            input.onkeyup = function() {
                input = document.activeElement;
                for (var i = 0; i < obj.length; i++) {
                    if (obj[i] == input) {
                        break;
                    }
                }
                input.focus();
                var s = document.selection.createRange();
                var re = input.createTextRange();
                var rc = re.duplicate();
                re.moveToBookmark(s.getBookmark());
                rc.setEndPoint("EndToStart", re);
                caretPositionAmp[i] = rc.text.length;
            }
        }
    }
}

window.onload = init;

jQuery.fn.extend({
    getSelection: function() {  // function for getting selection, and position of the selected text
        var input = this.jquery ? this[0] : this;
        var start;
        var end;
        var part;
        var number = 0;
        input.onmousedown = function() { // for IE 
            if (document.selection && typeof(input.selectionStart) != "number") {
                document.selection.empty();
            } else {
                window.getSelection().removeAllRanges();
            }
        }
        if (document.selection) {
            // part for IE and Opera
            var s = document.selection.createRange();
            var minus = 0;
            var position = 0;
            var minusEnd = 0;
            var re;
            var rc;
            var obj = document.getElementsByTagName('TEXTAREA');
            var pos = 0;
            for (pos; pos < obj.length; pos++) {
                if (obj[pos] == input) {
                    break;
                }
            }
            if (input.value.match(/\n/g) != null) {
                    number = input.value.match(/\n/g).length;// number of EOL simbols
            }
            if (s.text) {
                part = s.text;
                // OPERA support
                if (typeof(input.selectionStart) == "number") {
                    start = input.selectionStart;
                    end = input.selectionEnd;
                    // return null if the selected text not from the needed area
                    if (start == end) {
                        return { start: start, end: end, text: s.text, length: end - start };
                    }
                } else {
                    // IE support
                    re = input.createTextRange();
                    rc = re.duplicate();
                    firstRe = re.text;
                    re.moveToBookmark(s.getBookmark());
                    secondRe = re.text;
                    rc.setEndPoint("EndToStart", re);
                    // return null if the selectyed text not from the needed area
                    if (firstRe == secondRe && firstRe != s.text || rc.text.length > firstRe.length) {
                        return { start: caretPositionAmp[pos], end: caretPositionAmp[pos], text: "", length: 0 };
                    }
                    start = rc.text.length; 
                    end = rc.text.length + s.text.length;
                }
                // remove all EOL to have the same start and end positons as in MOZILLA
                if (number > 0) {
                    for (var i = 0; i <= number; i++) {
                        var w = input.value.indexOf("\n", position);
                        if (w != -1 && w < start) {
                            position = w + 1;
                            minus++;
                            minusEnd = minus;
                        } else if (w != -1 && w >= start && w <= end) {
                            if (w == start + 1) {
                                minus--;
                                minusEnd--;
                                position = w + 1;
                                continue;
                            }
                            position = w + 1;
                            minusEnd++;
                        } else {
                            i = number;
                        }
                    }
                }
                if (s.text.indexOf("\n", 0) == 1) {
                    minusEnd = minusEnd + 2;
                }
                start = start - minus;
                end = end - minusEnd;
                
                return { start: start, end: end, text: s.text, length: end - start };
            }
            input.focus ();
            if (typeof(input.selectionStart) == "number") {
                start = input.selectionStart;
            } else {
                s = document.selection.createRange();
                re = input.createTextRange();
                rc = re.duplicate();
                re.moveToBookmark(s.getBookmark());
                rc.setEndPoint("EndToStart", re);
                start = rc.text.length;
            }
            if (number > 0) {
                for (var i = 0; i <= number; i++) {
                    var w = input.value.indexOf("\n", position);
                    if (w != -1 && w < start) {
                        position = w + 1;
                        minus++;
                    } else {
                        i = number;
                    }
                }
            }
            start = start - minus;
            if (start == 0 && typeof(input.selectionStart) != "number") {
                start = caretPositionAmp[pos];
                end = caretPositionAmp[pos];
            }
            return { start: start, end: start, text: s.text, length: 0 };
        } else if (typeof(input.selectionStart) == "number" ) {
            start = input.selectionStart;
            end = input.selectionEnd;
            part = input.value.substring(input.selectionStart, input.selectionEnd);
            return { start: start, end: end, text: part, length: end - start };
        } else { return { start: undefined, end: undefined, text: undefined, length: undefined }; }
    },

    // function for the replacement of the selected text
    replaceSelection: function(inputStr) {
        var input = this.jquery ? this[0] : this; 
        //part for IE and Opera
        var start;
        var end;
        var position = 0;
        var rc;
        var re;
        var number = 0;
        var minus = 0;
        var mozScrollFix = ( input.scrollTop == undefined ) ? 0 : input.scrollTop;
        var obj = document.getElementsByTagName('TEXTAREA');
        var pos = 0;
        for (pos; pos < obj.length; pos++) {
            if (obj[pos] == input) {
                break;
            }
        }
        if (document.selection && typeof(input.selectionStart) != "number") {
            var s = document.selection.createRange();
            
            // IE support
            if (typeof(input.selectionStart) != "number") { // return null if the selected text not from the needed area
                var firstRe;
                var secondRe;
                re = input.createTextRange();
                rc = re.duplicate();
                firstRe = re.text;
                re.moveToBookmark(s.getBookmark());
                secondRe = re.text;
                try {
                    rc.setEndPoint("EndToStart", re);
                }
                catch(err) {
                    return this;
                }
                if (firstRe == secondRe && firstRe != s.text || rc.text.length > firstRe.length) {
                    return this;
                }
            }
            if (s.text) {
                part = s.text;
                if (input.value.match(/\n/g) != null) {
                    number = input.value.match(/\n/g).length;// number of EOL simbols
                }
                // IE support
                start = rc.text.length; 
                // remove all EOL to have the same start and end positons as in MOZILLA
                if (number > 0) {
                    for (var i = 0; i <= number; i++) {
                        var w = input.value.indexOf("\n", position);
                        if (w != -1 && w < start) {
                            position = w + 1;
                            minus++;
                            
                        } else {
                            i = number;
                        }
                    }
                }
                s.text = inputStr;
                caretPositionAmp[pos] = rc.text.length + inputStr.length;
                re.move("character", caretPositionAmp[pos]);
                document.selection.empty();
                input.blur();
            }
            return this;
        } else if (typeof(input.selectionStart) == "number" && // MOZILLA support
                input.selectionStart != input.selectionEnd) {
            
            start = input.selectionStart;
            end = input.selectionEnd;
            input.value = input.value.substr(0, start) + inputStr + input.value.substr(end);
            position = start + inputStr.length;
            input.setSelectionRange(position, position); 
            input.scrollTop = mozScrollFix;
            return this;
        }
        return this;
    },

    //Set Selection in text
    setSelection: function(startPosition, endPosition) {
        startPosition = parseInt(startPosition);
        endPosition = parseInt(endPosition);
        
        var input = this.jquery ? this[0] : this; 
        input.focus ();
        if (typeof(input.selectionStart) != "number") {
            re = input.createTextRange();
            if (re.text.length < endPosition) {
                endPosition = re.text.length+1;
            }
        }
        if (endPosition < startPosition) {
            return this;
        }
        if (document.selection) { 
            var number = 0;
            var plus = 0;
            var position = 0;
            var plusEnd = 0;
            if (typeof(input.selectionStart) != "number") { // IE
                re.collapse(true); 
                re.moveEnd('character', endPosition); 
                re.moveStart('character', startPosition); 
                re.select(); 
                return this;
            } else if (typeof(input.selectionStart) == "number") {      // Opera
                if (input.value.match(/\n/g) != null) {
                    number = input.value.match(/\n/g).length;// number of EOL simbols
                }
                if (number > 0) {
                    for (var i = 0; i <= number; i++) {
                        var w = input.value.indexOf("\n", position);
                        if (w != -1 && w < startPosition) {
                            position = w + 1;
                            plus++;
                            plusEnd = plus;
                        } else if (w != -1 && w >= startPosition && w <= endPosition) {
                            if (w == startPosition + 1) {
                                plus--;
                                plusEnd--;
                                position = w + 1;
                                continue;
                            }
                            position = w + 1;
                            plusEnd++;
                        } else {
                            i = number;
                        }
                    }
                }
                startPosition = startPosition + plus;
                endPosition = endPosition + plusEnd;
                input.selectionStart = startPosition; 
                input.selectionEnd = endPosition;
                input.focus ();
                return this;
            } else {
                input.focus ();
                return this;
            }
        }
        else if (input.selectionStart || input.selectionStart == 0) {   // MOZILLA support
            input.focus ();
            window.getSelection().removeAllRanges();
            input.selectionStart = startPosition; 
            input.selectionEnd = endPosition; 
            input.focus ();
            return this;
        } 
    },

    // insert text at current caret position
    insertAtCaretPos: function(inputStr) {
        var input = this.jquery ? this[0] : this; 
        var start;
        var end;
        var position;
        var s;
        var re;
        var rc;
        var point;
        var minus = 0;
        var number = 0;
        var mozScrollFix = ( input.scrollTop == undefined ) ? 0 : input.scrollTop; 
        var obj = document.getElementsByTagName('TEXTAREA');
        var pos = 0;
        for (pos; pos < obj.length; pos++) {
            if (obj[pos] == input) {
                break;
            }
        }
        input.focus();
        if (document.selection && typeof(input.selectionStart) != "number") {
            if (input.value.match(/\n/g) != null) {
                number = input.value.match(/\n/g).length;// number of EOL simbols
            }
            point = parseInt(caretPositionAmp[pos]);
            if (number > 0) {
                for (var i = 0; i <= number; i++) {
                    var w = input.value.indexOf("\n", position);
                    if (w != -1 && w <= point) {
                        position = w + 1;
                        point = point - 1;
                        minus++;
                    } 
                }
            }
        }
        caretPositionAmp[pos] = parseInt(caretPositionAmp[pos]);

        // IE
        input.onkeyup = function() { // for IE because it loses caret position when focus changed
            if (document.selection && typeof(input.selectionStart) != "number") {
                input.focus();
                s = document.selection.createRange();
                re = input.createTextRange();
                rc = re.duplicate();
                re.moveToBookmark(s.getBookmark());
                rc.setEndPoint("EndToStart", re);
                caretPositionAmp[pos] = rc.text.length;
            }
            
        }

        input.onmouseup = function() { // for IE because it loses caret position when focus changed
            if (document.selection && typeof(input.selectionStart) != "number") {
                input.focus();
                s = document.selection.createRange();
                re = input.createTextRange();
                rc = re.duplicate();
                re.moveToBookmark(s.getBookmark());
                rc.setEndPoint("EndToStart", re);
                caretPositionAmp[pos] = rc.text.length;
            }
        }

        if (document.selection && typeof(input.selectionStart) != "number") {
            s = document.selection.createRange();
            if (s.text.length != 0) {
                return this;
            }
            re = input.createTextRange();
            textLength = re.text.length;
            rc = re.duplicate();
            re.moveToBookmark(s.getBookmark());
            rc.setEndPoint("EndToStart", re);
            start = rc.text.length; 
            if (caretPositionAmp[pos] > 0 && start ==0) {
                minus = caretPositionAmp[pos] - minus;
                re.move("character", minus);
                re.select();
                s = document.selection.createRange();
                caretPositionAmp[pos] += inputStr.length;
            } else if (!(caretPositionAmp[pos] >= 0) && textLength ==0) {
                s = document.selection.createRange();
                caretPositionAmp[pos] = inputStr.length + textLength;
            } else if (!(caretPositionAmp[pos] >= 0) && start ==0) {
                re.move("character", textLength);
                re.select();
                s = document.selection.createRange();
                caretPositionAmp[pos] = inputStr.length + textLength;
            } else if (!(caretPositionAmp[pos] >= 0) && start > 0) { 
                re.move("character", 0);
                document.selection.empty();
                re.select();
                s = document.selection.createRange();
                caretPositionAmp[pos] = start + inputStr.length;
            } else if (caretPositionAmp[pos] >= 0 && caretPositionAmp[pos] == textLength) { 
                if (textLength != 0) {
                    re.move("character", textLength);
                    re.select();
                } else {
                    re.move("character", 0);
                }
                s = document.selection.createRange();
                caretPositionAmp[pos] = inputStr.length + textLength;
            } else if (caretPositionAmp[pos] >= 0 && start != 0 && caretPositionAmp[pos] >= start) { 
                minus = caretPositionAmp[pos] - start;
                re.move("character", minus);
                document.selection.empty();
                re.select();
                s = document.selection.createRange();
                caretPositionAmp[pos] = caretPositionAmp[pos] + inputStr.length; 
            } else if (caretPositionAmp[pos] >= 0 && start != 0 && caretPositionAmp[pos] < start) { 
                re.move("character", 0);
                document.selection.empty();
                re.select();
                s = document.selection.createRange();
                caretPositionAmp[pos] = caretPositionAmp[pos] + inputStr.length; 
            } else { 
                document.selection.empty();
                re.select();
                s = document.selection.createRange();
                caretPositionAmp[pos] = caretPositionAmp[pos] + inputStr.length; 
            } 
            s.text = inputStr; 
            input.focus();

            return this;
        } else if (typeof(input.selectionStart) == "number" && // MOZILLA support
                input.selectionStart == input.selectionEnd) {
            position = input.selectionStart + inputStr.length;
            start = input.selectionStart;
            end = input.selectionEnd;
            input.value = input.value.substr(0, start) + inputStr + input.value.substr(end);
            input.setSelectionRange(position, position); 
            input.scrollTop = mozScrollFix; 
            return this;
        }
        return this;
    },

    // Set caret position
    setCaretPos: function(inputStr) {
        var input = this.jquery ? this[0] : this; 
        var s;
        var re;
        var position;
        var number = 0;
        var minus = 0;
        var w;
        var obj = document.getElementsByTagName('TEXTAREA');
        var pos = 0;
        for (pos; pos < obj.length; pos++) {
            if (obj[pos] == input) {
                break;
            }
        }
        input.focus();
        if (parseInt(inputStr) == 0) {
            return this;
        }
        //if (document.selection && typeof(input.selectionStart) == "number") {
        if (parseInt(inputStr) > 0) {
            inputStr = parseInt(inputStr) - 1;
            if (document.selection && typeof(input.selectionStart) == "number" && input.selectionStart == input.selectionEnd) {
                if (input.value.match(/\n/g) != null) {
                    number = input.value.match(/\n/g).length;// number of EOL simbols
                }
                if (number > 0) {
                    for (var i = 0; i <= number; i++) {
                        w = input.value.indexOf("\n", position);
                        if (w != -1 && w <= inputStr) {
                            position = w + 1;
                            inputStr = parseInt(inputStr) + 1;
                        } 
                    }
                }
            }
        } 
        else if (parseInt(inputStr) < 0) {
            inputStr = parseInt(inputStr) + 1;
            if (document.selection && typeof(input.selectionStart) != "number") {
                inputStr = input.value.length + parseInt(inputStr);
                if (input.value.match(/\n/g) != null) {
                    number = input.value.match(/\n/g).length;// number of EOL simbols
                }
                if (number > 0) {
                    for (var i = 0; i <= number; i++) {
                        w = input.value.indexOf("\n", position);
                        if (w != -1 && w <= inputStr) {
                            position = w + 1;
                            inputStr = parseInt(inputStr) - 1;
                            minus += 1;
                        } 
                    }
                    inputStr = inputStr + minus - number;
                }
            } else if (document.selection && typeof(input.selectionStart) == "number") {
                inputStr = input.value.length + parseInt(inputStr);
                if (input.value.match(/\n/g) != null) {
                    number = input.value.match(/\n/g).length;// number of EOL simbols
                }
                if (number > 0) {
                    inputStr = parseInt(inputStr) - number;
                    for (var i = 0; i <= number; i++) {
                        w = input.value.indexOf("\n", position);
                        if (w != -1 && w <= (inputStr)) {
                            position = w + 1;
                            inputStr = parseInt(inputStr) + 1;
                            minus += 1;
                        } 
                    }
                }
            } else { inputStr = input.value.length + parseInt(inputStr); }
        } else { return this; }
        // IE
        if (document.selection && typeof(input.selectionStart) != "number") {
            s = document.selection.createRange();
            if (s.text != 0) {
                return this;
            }
            re = input.createTextRange();
            re.collapse(true);
            re.moveEnd('character', inputStr);
            re.moveStart('character', inputStr);
            re.select();
            caretPositionAmp[pos] = inputStr;
            return this;
        } else if (typeof(input.selectionStart) == "number" && // MOZILLA support
                input.selectionStart == input.selectionEnd) {
            input.setSelectionRange(inputStr, inputStr); 
            return this;
        }
        return this;
    },

    countCharacters: function(str) {
        var input = this.jquery ? this[0] : this;
        if (input.value.match(/\r/g) != null) {
            return input.value.length - input.value.match(/\r/g).length;
        }
        return input.value.length;
    },

    setMaxLength: function(max, f) {
        this.each(function() {
            var input = this.jquery ? this[0] : this;
            var type = input.type;
            var isSelected;    
            var maxCharacters;
            // remove limit if input is a negative number
            if (parseInt(max) < 0) {
                max=100000000;
            }
            if (type == "text") {
                input.maxLength = max;
            }
            if (type == "textarea" || type == "text") {
                input.onkeypress = function(e) {
                    var spacesR = input.value.match(/\r/g);
                    maxCharacters = max;
                    if (spacesR != null) {
                        maxCharacters = parseInt(maxCharacters) + spacesR.length;
                    }
                    // get event
                    var key = e || event;
                    var keyCode = key.keyCode;
                    // check if any part of text is selected
                    if (document.selection) {
                        isSelected = document.selection.createRange().text.length > 0;
                    } else {
                        isSelected = input.selectionStart != input.selectionEnd;
                    }
                    if (input.value.length >= maxCharacters && (keyCode > 47 || keyCode == 32 ||
                            keyCode == 0 || keyCode == 13) && !key.ctrlKey && !key.altKey && !isSelected) {
                        input.value = input.value.substring(0,maxCharacters);
                        if (typeof(f) == "function") { f() } //callback function
                        return false;
                    }
                }
                input.onkeyup = function() { 
                    var spacesR = input.value.match(/\r/g);
                    var plus = 0;
                    var position = 0;
                    maxCharacters = max;
                    if (spacesR != null) {
                        for (var i = 0; i <= spacesR.length; i++) {
                            if (input.value.indexOf("\n", position) <= parseInt(max)) {
                                plus++;
                                position = input.value.indexOf("\n", position) + 1;
                            }
                        }
                        maxCharacters = parseInt(max) + plus;
                    } 
                    if (input.value.length > maxCharacters) {  
                        input.value = input.value.substring(0, maxCharacters); 
                        if (typeof(f) == "function") { f() }
                        return this;
                    }
                }
            } else { return this; }
        })
        return this;
    }
}); 
//A-Tools End


//bubble
	//later. ****
//bubble end

	function IsNumeric(expression) {

	var nums = "0123456789";

	if (expression.length==0)return(false);
		for (var n=0; n < expression.length; n++){
			if(nums.indexOf(expression.charAt(n))==-1)return(false);
		}
		return(true);
	}

//query/plugin definitions//

window.Error = function(msg) 
{
    alert(msg); 
}

$(document).ready(function(){
	
	//Carousel / Koray
	//-menu
	var litems = $("#images>img").size();
	var a = 0;
	while(litems>0){
		a++
		$("#cimgs").append("<li onclick='"+a+"'>"+litems+"</li>");
		litems = litems-1;
	}

	//-images
	$("#images > img").first().addClass("show");
	var cimgtitle = $("#images > img").first().attr("title")
	$("#carousel > #title").html(cimgtitle);
	$("#cimgs > li").last().addClass("selected");
	var mypic;
	rotationInterval = setInterval(function(){
		mypic = $('#images > .show');
		myli =  $('#cimgs > .selected');
		if(mypic.next().length){
			mypic.next().fadeIn().addClass("show");
			cimgtitle = mypic.next().attr("title");
			myli.prev().addClass("selected");
		}else{
			$("#images > img").first().fadeIn().addClass("show");
			cimgtitle = $("#images > img").first().attr("title");
			$("#cimgs > li").last().addClass("selected");
		}
		$("#carousel > #title").html(cimgtitle);
		mypic.fadeOut().removeClass("show");
		myli.removeClass("selected");
	}, 5000);
		
//double submit
$.fn.preventDoubleSubmit = function() {
 $(this).submit(function() {
    if (this.beenSubmitted)
      return false;
    else
      this.beenSubmitted = true;
  });
};

$('#loginform').preventDoubleSubmit();
$('#signupform').preventDoubleSubmit();
//double submit end

/*
	$('#loginb').click(function() { 
		loginf();
	});
*/
	$('#signb').click(function() { 
		signup();
	});

	$("#getvideo").click(function(){
		getVideoData($("#url").val());
	});

	$("span#add").click(function(){
		var elem = $(this);

		$.ajax({
		  url: '/qfuncs.php?ftype=addgametolist&data='+$(this).attr("rel"),
		  success: function(data) {
			  if(jQuery.trim(data)==1){
					$(elem).children().attr("src","/images/miniadd2.png");
			  }
			  else{
				alert('Oyun listenize eklenemedi, zaten listenizde olabilir.');
			  }
		  }
		});

	});

	$(".gamelist > li").mouseover(function(){
			$(this).find(".gametitler").animate({"opacity":"0.8","bottom":"0"},300)
		}).mouseleave(function(){
			$(this).find(".gametitler").animate({"opacity":"0","bottom":"-36"},300)
		});

		$("img[rel='video']").click(function() { 
			$('#playerarea').animate({
				width: 640,//$(this).width(),
				height: 385//$(this).height()
			});

			var sizes = $(this).attr('size');
			sizes = sizes.split(',');

			$('#playerarea').html('<br/>Yükleniyor');

			$.ajax({
				type: "GET",
				url: "/media.php",
				data: "media="+$(this).attr('id'),
				cache: false,
				success: function(html){
					$("#playerarea").html(html);
					$('#playerarea').animate({
						width: sizes[0],
						height: sizes[1]
					});

				}
			});

		});
		//endajx

	//rounded corners
	$('#gamermenu').corner("6px top");
	$('.mainmenu').corner("6px bottom");
	
	$('.md').corner("6px");
	$('.mtv').corner("6px");
	$('.mntw').corner("6px");
	$('.madd').corner("6px");
	$('.rightbar').corner("6px");
	$('.rightbar2').corner("6px tl bl");
	$('.contentholder').corner("6px");
	$('.contentbotholder').corner("6px");
	$('.blogpiclist').corner("6px");
	$('.beditor').corner("6px top");
	$('.tupmain').corner("6px");
	$('.tupthumb').corner("6px");
	$('.gcritic').corner("6px");
	$('.hcritic').corner("6px");
	$('#login').corner("6px bottom");

	$('#login').click(function(){
		$('#dialog').dialog('open');
		return false;
	});

	//@Block
	$("#gamermenu").animate({opacity: 0.0}, 100);

	$('.ubgamermenu').toggle(
		function (){ 
		$(".myfriendlist > h4 > a").click();
		$('#gamermenu').css("display","block");
		$("#gamermenu").animate({opacity: 1.0}, 300);
		},
		function (){ 
		$("#gamermenu").animate({
		opacity: 0.0}, 300,function(){$('#gamermenu').css("display","none");});
		}
		);
	//GamerMenu
	$('#gm1').click(function(){window.location.replace("/uye/oyunlar");
		return false;
	});
	$('#gm2').click(function(){//window.location.replace("/uye/arkadaslar");
		$(".myfriendlist").show("slow");
		$(".ubgamermenu").click();
		return false;
	});
	$('#gm3').click(function(){alert("Ekipler yakında.");
		return false;
	});
	$('#gm4').click(function(){alert("Gruplarım yakında.");
		return false;
	});
	$('#gm5').click(function(){window.location.replace("/ekle/yazi");
		return false;
	});


		/*.toggle(
		function (){ 
			$(".beditor").animate({bottom: "0px"}, 300);
			$(".beditor").css("display", "block");
		},
		function (){ 
			$(".beditor").animate({bottom: "-600px"}, 300,function(){
					$('.beditor').css("display","none");
					}
					);
		}
	);
	?/
	//GM End
	/*

		$('#bigEditor').toggle(
		function (){ 
			$(".beditor").animate({bottom: "0px"}, 300);
		},
		function (){ 
			$(".beditor").animate({bottom: "-600px"}, 300);
		}
		);
	*/

	$(".myfriendlist > h4 > a").click(function(){
		$(".myfriendlist").hide("slow");
	});

	if($("#commenttbox").length){ $("#commenttbox").Watermark("Yorumunuzu yazın"); }
	if($("#forgotemail").length){ $("#forgotemail").Watermark("E-Mail"); }
	$(".draghandler").draggable({ axis: "x", containment: "parent", stop: function(event, ui){
			var lft = $(this).css("left");
			var form = $(this).attr("form");
			lng = lft.length-2;
			lft = lft.substr(0,lng);
			if(lft<66){ $(this).animate({left:0}); }
			else{
				$(this).draggable("destroy");
				$("#"+form).submit();
			}
		}
	});


$('#tuppost').click(function(){

	var content = document.getElementById("usertextbox").value;
	var hf = 0;
	var ff = 0;

	if ($('#homefeed:checked').is(':checked')) {
		hf = document.getElementById("homefeed").value;
	}

	if ($('#friendfeed:checked').is(':checked')) {
		ff = document.getElementById("friendfeed").value;
	}

	if (content!="")
	{
		var q = "feed="+content+"&hf="+hf+"&ff="+ff;
		$.ajax({
			type: "POST",
			url: "/post/tup",
			data: q,
			ajaxStart: function() { 
				$("#tupstatus").html("Giriş yapılıyor"); 
				$(".usertextbox").hide(); 
			},
			success: function(veri) { 
				var errors=new Array();
				veri = Number(veri);
				errors[0]="";
				errors[1]="Bir hata oluştu.";
				errors[2]="Mesajınız gönderildi.";
				errors[3]="Bu kullanıcı bulunamadı.";
				if (veri==0){
					window.location.replace("/uye/feed/benim");
				}else{
					$(".utbinfos").html("<span>Paylaş:</span>");
					$("#tupstatus").html(errors[veri]);
				}
				//error Check
				//$("#tupstatus").html(veri);
			},
			dataType: "html"
		  });

	}else{
		$("#tupstatus").html("Mesaj alanı boş.").delay(2000).html("");
	}

});


/*
 * FancyBox - jQuery Plugin
 * Simple and fancy lightbox alternative
 *
 * Examples and documentation at: http://fancybox.net
 * 
 * Copyright (c) 2008 - 2010 Janis Skarnelis
 * That said, it is hardly a one-person project. Many people have submitted bugs, code, and offered their advice freely. Their support is greatly appreciated.
 * 
 * Version: 1.3.2 (20/10/2010)
 * Requires: jQuery v1.3+
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

;(function(a){var m,t,u,f,D,h,E,n,z,A,q=0,e={},o=[],p=0,c={},l=[],I=null,v=new Image,J=/\.(jpg|gif|png|bmp|jpeg)(.*)?$/i,W=/[^\.]\.(swf)\s*$/i,K,L=1,y=0,s="",r,j,i=false,B=a.extend(a("<div/>")[0],{prop:0}),M=a.browser.msie&&a.browser.version<7&&!window.XMLHttpRequest,N=function(){t.hide();v.onerror=v.onload=null;I&&I.abort();m.empty()},O=function(){if(false===e.onError(o,q,e)){t.hide();i=false}else{e.titleShow=false;e.width="auto";e.height="auto";m.html('<p id="fancybox-error">The requested content cannot be loaded.<br />Please try again later.</p>');
F()}},H=function(){var b=o[q],d,g,k,C,P,w;N();e=a.extend({},a.fn.fancybox.defaults,typeof a(b).data("fancybox")=="undefined"?e:a(b).data("fancybox"));w=e.onStart(o,q,e);if(w===false)i=false;else{if(typeof w=="object")e=a.extend(e,w);k=e.title||(b.nodeName?a(b).attr("title"):b.title)||"";if(b.nodeName&&!e.orig)e.orig=a(b).children("img:first").length?a(b).children("img:first"):a(b);if(k===""&&e.orig&&e.titleFromAlt)k=e.orig.attr("alt");d=e.href||(b.nodeName?a(b).attr("href"):b.href)||null;if(/^(?:javascript)/i.test(d)||
d=="#")d=null;if(e.type){g=e.type;if(!d)d=e.content}else if(e.content)g="html";else if(d)g=d.match(J)?"image":d.match(W)?"swf":a(b).hasClass("iframe")?"iframe":d.indexOf("#")===0?"inline":"ajax";if(g){if(g=="inline"){b=d.substr(d.indexOf("#"));g=a(b).length>0?"inline":"ajax"}e.type=g;e.href=d;e.title=k;if(e.autoDimensions&&e.type!=="iframe"&&e.type!=="swf"){e.width="auto";e.height="auto"}if(e.modal){e.overlayShow=true;e.hideOnOverlayClick=false;e.hideOnContentClick=false;e.enableEscapeButton=false;
e.showCloseButton=false}e.padding=parseInt(e.padding,10);e.margin=parseInt(e.margin,10);m.css("padding",e.padding+e.margin);a(".fancybox-inline-tmp").unbind("fancybox-cancel").bind("fancybox-change",function(){a(this).replaceWith(h.children())});switch(g){case "html":m.html(e.content);F();break;case "inline":if(a(b).parent().is("#fancybox-content")===true){i=false;break}a('<div class="fancybox-inline-tmp" />').hide().insertBefore(a(b)).bind("fancybox-cleanup",function(){a(this).replaceWith(h.children())}).bind("fancybox-cancel",
function(){a(this).replaceWith(m.children())});a(b).appendTo(m);F();break;case "image":i=false;a.fancybox.showActivity();v=new Image;v.onerror=function(){O()};v.onload=function(){i=true;v.onerror=v.onload=null;e.width=v.width;e.height=v.height;a("<img />").attr({id:"fancybox-img",src:v.src,alt:e.title}).appendTo(m);Q()};v.src=d;break;case "swf":C='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+e.width+'" height="'+e.height+'"><param name="movie" value="'+d+'"></param>';P="";
a.each(e.swf,function(x,G){C+='<param name="'+x+'" value="'+G+'"></param>';P+=" "+x+'="'+G+'"'});C+='<embed src="'+d+'" type="application/x-shockwave-flash" width="'+e.width+'" height="'+e.height+'"'+P+"></embed></object>";m.html(C);F();break;case "ajax":i=false;a.fancybox.showActivity();e.ajax.win=e.ajax.success;I=a.ajax(a.extend({},e.ajax,{url:d,data:e.ajax.data||{},error:function(x){x.status>0&&O()},success:function(x,G,U){if(U.status==200){if(typeof e.ajax.win=="function"){w=e.ajax.win(d,x,G,
U);if(w===false){t.hide();return}else if(typeof w=="string"||typeof w=="object")x=w}m.html(x);F()}}}));break;case "iframe":Q()}}else O()}},F=function(){m.width(e.width);m.height(e.height);if(e.width=="auto")e.width=m.width();if(e.height=="auto")e.height=m.height();Q()},Q=function(){var b,d;t.hide();if(f.is(":visible")&&false===c.onCleanup(l,p,c)){a.event.trigger("fancybox-cancel");i=false}else{i=true;a(h.add(u)).unbind();a(window).unbind("resize.fb scroll.fb");a(document).unbind("keydown.fb");f.is(":visible")&&
c.titlePosition!=="outside"&&f.css("height",f.height());l=o;p=q;c=e;if(c.overlayShow){u.css({"background-color":c.overlayColor,opacity:c.overlayOpacity,cursor:c.hideOnOverlayClick?"pointer":"auto",height:a(document).height()});if(!u.is(":visible")){M&&a("select:not(#fancybox-tmp select)").filter(function(){return this.style.visibility!=="hidden"}).css({visibility:"hidden"}).one("fancybox-cleanup",function(){this.style.visibility="inherit"});u.show()}}else u.hide();h.get(0).scrollTop=0;h.get(0).scrollLeft=
0;j=X();s=c.title||"";y=0;n.empty().removeAttr("style").removeClass();if(c.titleShow!==false){if(a.isFunction(c.titleFormat))b=c.titleFormat(s,l,p,c);else b=s&&s.length?c.titlePosition=="float"?'<table id="fancybox-title-float-wrap" cellpadding="0" cellspacing="0"><tr><td id="fancybox-title-float-left"></td><td id="fancybox-title-float-main">'+s+'</td><td id="fancybox-title-float-right"></td></tr></table>':'<div id="fancybox-title-'+c.titlePosition+'">'+s+"</div>":false;s=b;if(!(!s||s==="")){n.addClass("fancybox-title-"+
c.titlePosition).html(s).appendTo("body").show();switch(c.titlePosition){case "inside":n.css({width:j.width-c.padding*2,marginLeft:c.padding,marginRight:c.padding});y=n.outerHeight(true);n.appendTo(D);j.height+=y;break;case "over":n.css({marginLeft:c.padding,width:j.width-c.padding*2,bottom:c.padding}).appendTo(D);break;case "float":n.css("left",parseInt((n.width()-j.width-40)/2,10)*-1).appendTo(f);break;default:n.css({width:j.width-c.padding*2,paddingLeft:c.padding,paddingRight:c.padding}).appendTo(f)}}}n.hide();
if(f.is(":visible")){a(E.add(z).add(A)).hide();b=f.position();r={top:b.top,left:b.left,width:f.width(),height:f.height()};d=r.width==j.width&&r.height==j.height;h.fadeTo(c.changeFade,0.3,function(){var g=function(){h.html(m.contents()).fadeTo(c.changeFade,1,R)};a.event.trigger("fancybox-change");h.empty().removeAttr("filter").css({"border-width":c.padding,width:j.width-c.padding*2,height:c.type=="image"||c.type=="swf"||c.type=="iframe"?j.height-y-c.padding*2:"auto"});if(d)g();else{B.prop=0;a(B).animate({prop:1},
{duration:c.changeSpeed,easing:c.easingChange,step:S,complete:g})}})}else{f.removeAttr("style");h.css("border-width",c.padding);if(c.transitionIn=="elastic"){r=V();h.html(m.contents());f.show();if(c.opacity)j.opacity=0;B.prop=0;a(B).animate({prop:1},{duration:c.speedIn,easing:c.easingIn,step:S,complete:R})}else{c.titlePosition=="inside"&&y>0&&n.show();h.css({width:j.width-c.padding*2,height:c.type=="image"||c.type=="swf"||c.type=="iframe"?j.height-y-c.padding*2:"auto"}).html(m.contents());f.css(j).fadeIn(c.transitionIn==
"none"?0:c.fadeIn,R)}}}},Y=function(){if(c.enableEscapeButton||c.enableKeyboardNav)a(document).bind("keydown.fb",function(b){if(b.keyCode==27&&c.enableEscapeButton){b.preventDefault();a.fancybox.close()}else if((b.keyCode==37||b.keyCode==39)&&c.enableKeyboardNav&&b.target.tagName!=="INPUT"&&b.target.tagName!=="TEXTAREA"&&b.target.tagName!=="SELECT"){b.preventDefault();a.fancybox[b.keyCode==37?"prev":"next"]()}});if(c.showNavArrows){if(c.cyclic&&l.length>1||p!==0)z.show();if(c.cyclic&&l.length>1||
p!=l.length-1)A.show()}else{z.hide();A.hide()}},R=function(){if(!a.support.opacity){h.get(0).style.removeAttribute("filter");f.get(0).style.removeAttribute("filter")}f.css("height","auto");c.type!=="image"&&c.type!=="swf"&&c.type!=="iframe"&&h.css("height","auto");s&&s.length&&n.show();c.showCloseButton&&E.show();Y();c.hideOnContentClick&&h.bind("click",a.fancybox.close);c.hideOnOverlayClick&&u.bind("click",a.fancybox.close);a(window).bind("resize.fb",a.fancybox.resize);c.centerOnScroll&&a(window).bind("scroll.fb",
a.fancybox.center);if(c.type=="iframe")a('<iframe id="fancybox-frame" name="fancybox-frame'+(new Date).getTime()+'" frameborder="0" hspace="0" '+(a.browser.msie?'allowtransparency="true""':"")+' scrolling="'+e.scrolling+'" src="'+c.href+'"></iframe>').appendTo(h);f.show();i=false;a.fancybox.center();c.onComplete(l,p,c);var b,d;if(l.length-1>p){b=l[p+1].href;if(typeof b!=="undefined"&&b.match(J)){d=new Image;d.src=b}}if(p>0){b=l[p-1].href;if(typeof b!=="undefined"&&b.match(J)){d=new Image;d.src=b}}},
S=function(b){var d={width:parseInt(r.width+(j.width-r.width)*b,10),height:parseInt(r.height+(j.height-r.height)*b,10),top:parseInt(r.top+(j.top-r.top)*b,10),left:parseInt(r.left+(j.left-r.left)*b,10)};if(typeof j.opacity!=="undefined")d.opacity=b<0.5?0.5:b;f.css(d);h.css({width:d.width-c.padding*2,height:d.height-y*b-c.padding*2})},T=function(){return[a(window).width()-c.margin*2,a(window).height()-c.margin*2,a(document).scrollLeft()+c.margin,a(document).scrollTop()+c.margin]},X=function(){var b=
T(),d={},g=c.autoScale,k=c.padding*2;d.width=c.width.toString().indexOf("%")>-1?parseInt(b[0]*parseFloat(c.width)/100,10):c.width+k;d.height=c.height.toString().indexOf("%")>-1?parseInt(b[1]*parseFloat(c.height)/100,10):c.height+k;if(g&&(d.width>b[0]||d.height>b[1]))if(e.type=="image"||e.type=="swf"){g=c.width/c.height;if(d.width>b[0]){d.width=b[0];d.height=parseInt((d.width-k)/g+k,10)}if(d.height>b[1]){d.height=b[1];d.width=parseInt((d.height-k)*g+k,10)}}else{d.width=Math.min(d.width,b[0]);d.height=
Math.min(d.height,b[1])}d.top=parseInt(Math.max(b[3]-20,b[3]+(b[1]-d.height-40)*0.5),10);d.left=parseInt(Math.max(b[2]-20,b[2]+(b[0]-d.width-40)*0.5),10);return d},V=function(){var b=e.orig?a(e.orig):false,d={};if(b&&b.length){d=b.offset();d.top+=parseInt(b.css("paddingTop"),10)||0;d.left+=parseInt(b.css("paddingLeft"),10)||0;d.top+=parseInt(b.css("border-top-width"),10)||0;d.left+=parseInt(b.css("border-left-width"),10)||0;d.width=b.width();d.height=b.height();d={width:d.width+c.padding*2,height:d.height+
c.padding*2,top:d.top-c.padding-20,left:d.left-c.padding-20}}else{b=T();d={width:c.padding*2,height:c.padding*2,top:parseInt(b[3]+b[1]*0.5,10),left:parseInt(b[2]+b[0]*0.5,10)}}return d},Z=function(){if(t.is(":visible")){a("div",t).css("top",L*-40+"px");L=(L+1)%12}else clearInterval(K)};a.fn.fancybox=function(b){if(!a(this).length)return this;a(this).data("fancybox",a.extend({},b,a.metadata?a(this).metadata():{})).unbind("click.fb").bind("click.fb",function(d){d.preventDefault();if(!i){i=true;a(this).blur();
o=[];q=0;d=a(this).attr("rel")||"";if(!d||d==""||d==="nofollow")o.push(this);else{o=a("a[rel="+d+"], area[rel="+d+"]");q=o.index(this)}H()}});return this};a.fancybox=function(b,d){var g;if(!i){i=true;g=typeof d!=="undefined"?d:{};o=[];q=parseInt(g.index,10)||0;if(a.isArray(b)){for(var k=0,C=b.length;k<C;k++)if(typeof b[k]=="object")a(b[k]).data("fancybox",a.extend({},g,b[k]));else b[k]=a({}).data("fancybox",a.extend({content:b[k]},g));o=jQuery.merge(o,b)}else{if(typeof b=="object")a(b).data("fancybox",
a.extend({},g,b));else b=a({}).data("fancybox",a.extend({content:b},g));o.push(b)}if(q>o.length||q<0)q=0;H()}};a.fancybox.showActivity=function(){clearInterval(K);t.show();K=setInterval(Z,66)};a.fancybox.hideActivity=function(){t.hide()};a.fancybox.next=function(){return a.fancybox.pos(p+1)};a.fancybox.prev=function(){return a.fancybox.pos(p-1)};a.fancybox.pos=function(b){if(!i){b=parseInt(b);o=l;if(b>-1&&b<l.length){q=b;H()}else if(c.cyclic&&l.length>1){q=b>=l.length?0:l.length-1;H()}}};a.fancybox.cancel=
function(){if(!i){i=true;a.event.trigger("fancybox-cancel");N();e.onCancel(o,q,e);i=false}};a.fancybox.close=function(){function b(){u.fadeOut("fast");n.empty().hide();f.hide();a.event.trigger("fancybox-cleanup");h.empty();c.onClosed(l,p,c);l=e=[];p=q=0;c=e={};i=false}if(!(i||f.is(":hidden"))){i=true;if(c&&false===c.onCleanup(l,p,c))i=false;else{N();a(E.add(z).add(A)).hide();a(h.add(u)).unbind();a(window).unbind("resize.fb scroll.fb");a(document).unbind("keydown.fb");h.find("iframe").attr("src",M&&
/^https/i.test(window.location.href||"")?"javascript:void(false)":"about:blank");c.titlePosition!=="inside"&&n.empty();f.stop();if(c.transitionOut=="elastic"){r=V();var d=f.position();j={top:d.top,left:d.left,width:f.width(),height:f.height()};if(c.opacity)j.opacity=1;n.empty().hide();B.prop=1;a(B).animate({prop:0},{duration:c.speedOut,easing:c.easingOut,step:S,complete:b})}else f.fadeOut(c.transitionOut=="none"?0:c.speedOut,b)}}};a.fancybox.resize=function(){u.is(":visible")&&u.css("height",a(document).height());
a.fancybox.center(true)};a.fancybox.center=function(b){var d,g;if(!i){g=b===true?1:0;d=T();!g&&(f.width()>d[0]||f.height()>d[1])||f.stop().animate({top:parseInt(Math.max(d[3]-20,d[3]+(d[1]-h.height()-40)*0.5-c.padding)),left:parseInt(Math.max(d[2]-20,d[2]+(d[0]-h.width()-40)*0.5-c.padding))},typeof b=="number"?b:200)}};a.fancybox.init=function(){if(!a("#fancybox-wrap").length){a("body").append(m=a('<div id="fancybox-tmp"></div>'),t=a('<div id="fancybox-loading"><div></div></div>'),u=a('<div id="fancybox-overlay"></div>'),
f=a('<div id="fancybox-wrap"></div>'));D=a('<div id="fancybox-outer"></div>').append('<div class="fancybox-bg" id="fancybox-bg-n"></div><div class="fancybox-bg" id="fancybox-bg-ne"></div><div class="fancybox-bg" id="fancybox-bg-e"></div><div class="fancybox-bg" id="fancybox-bg-se"></div><div class="fancybox-bg" id="fancybox-bg-s"></div><div class="fancybox-bg" id="fancybox-bg-sw"></div><div class="fancybox-bg" id="fancybox-bg-w"></div><div class="fancybox-bg" id="fancybox-bg-nw"></div>').appendTo(f);
D.append(h=a('<div id="fancybox-content"></div>'),E=a('<a id="fancybox-close"></a>'),n=a('<div id="fancybox-title"></div>'),z=a('<a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a>'),A=a('<a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a>'));E.click(a.fancybox.close);t.click(a.fancybox.cancel);z.click(function(b){b.preventDefault();a.fancybox.prev()});A.click(function(b){b.preventDefault();a.fancybox.next()});
a.fn.mousewheel&&f.bind("mousewheel.fb",function(b,d){b.preventDefault();a.fancybox[d>0?"prev":"next"]()});a.support.opacity||f.addClass("fancybox-ie");if(M){t.addClass("fancybox-ie6");f.addClass("fancybox-ie6");a('<iframe id="fancybox-hide-sel-frame" src="'+(/^https/i.test(window.location.href||"")?"javascript:void(false)":"about:blank")+'" scrolling="no" border="0" frameborder="0" tabindex="-1"></iframe>').prependTo(D)}}};a.fn.fancybox.defaults={padding:10,margin:40,opacity:false,modal:false,cyclic:false,
scrolling:"auto",width:560,height:340,autoScale:true,autoDimensions:true,centerOnScroll:false,ajax:{},swf:{wmode:"transparent"},hideOnOverlayClick:true,hideOnContentClick:false,overlayShow:true,overlayOpacity:0.7,overlayColor:"#777",titleShow:true,titlePosition:"float",titleFormat:null,titleFromAlt:false,transitionIn:"fade",transitionOut:"fade",speedIn:300,speedOut:300,changeSpeed:300,changeFade:"fast",easingIn:"swing",easingOut:"swing",showCloseButton:true,showNavArrows:true,enableEscapeButton:true,
enableKeyboardNav:true,onStart:function(){},onCancel:function(){},onComplete:function(){},onCleanup:function(){},onClosed:function(){},onError:function(){}};a(document).ready(function(){a.fancybox.init()})})(jQuery);

/*fancybox end */


var timeout    = 500;
var closetimer = 0;
var ddmenuitem = 0;

function hmenu_open()
{  hmenu_canceltimer();
   hmenu_close();
   ddmenuitem = $(this).find('ul').css('visibility', 'visible');}

function hmenu_close()
{  if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');}

function hmenu_timer()
{  closetimer = window.setTimeout(hmenu_close, timeout);}

function hmenu_canceltimer()
{  if(closetimer)
   {  window.clearTimeout(closetimer);
      closetimer = null;}}

$(document).ready(function(){
	$('#hmenu > li').bind('mouseover', hmenu_open);
	$('#hmenu > li').bind('mouseout',  hmenu_timer);

	$("a[rel=lightbox]").fancybox({
				'titlePosition' 	: 'over',
				'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
					return '<span id="fancybox-title-over">Görsel ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
				}
			});


	if ($('.twits').length) {
		$(".twits").html("Yükleniyor");
		$(".twits").load("/qfuncs.php?ftype=twitter&data=1");
	} 

//Scrolling Menu
	$(window).scroll(function(){
	    if($(window).scrollTop()>122){
	        nheight = $(window).scrollTop();
	        $('.mainmenu').css({
	            'position':'fixed',
	            'z-index':100,
	            'top':'0',
				'left':'10%'
	        });
	    }else{
	        $('.mainmenu').css({
	            'position':'',
	            'top':'',
				'left':''
	        });
	    }
	});
//Scrolling Menu End
});

document.onclick = hmenu_close;

//ESC Close
/*
$(document).keyup(function(e) { 
	if (e.which == 27) {
		hmenu_close();
	}
});
*/
//ESC Close /


//Game ADD Options

//Game Add End

//GrowingInput
/*
Script: GrowingInput.js
	Alters the size of an input depending on its content

	License:
		MIT-style license.

	Authors:
		Guillermo Rauch
*/
$.GrowingInput = function(element, options){
	
	var value, lastValue, calc;
	
	options = $.extend({
		min: 0,
		max: null,
		startWidth: 15,
		correction: 15
	}, options);
	
	element = $(element).data('growing', this);
	
	var self = this;
	var init = function(){
		calc = $('<span></span>').css({
			'float': 'left',
			'display': 'inline-block',
			'position': 'absolute',
			'left': -1000
		}).insertAfter(element);
		$.each(['font-size', 'font-family', 'padding-left', 'padding-top', 'padding-bottom', 
		 'padding-right', 'border-left', 'border-right', 'border-top', 'border-bottom', 
		 'word-spacing', 'letter-spacing', 'text-indent', 'text-transform'], function(i, p){				
				calc.css(p, element.css(p));
		});
		element.blur(resize).keyup(resize).keydown(resize).keypress(resize);
		resize();
	};
	
	var calculate = function(chars){
		calc.text(chars);
		var width = calc.width();
		return (width ? width : options.startWidth) + options.correction;
	};
	
	var resize = function(){
		lastValue = value;
		value = element.val();
		var retValue = value;		
		if(chk(options.min) && value.length < options.min){
			if(chk(lastValue) && (lastValue.length <= options.min)) return;
			retValue = str_pad(value, options.min, '-');
		} else if(chk(options.max) && value.length > options.max){
			if(chk(lastValue) && (lastValue.length >= options.max)) return;
			retValue = value.substr(0, options.max);
		}
		element.width(calculate(retValue));
		return self;
	};
	
	this.resize = resize;
	init();
};

var chk = function(v){ return !!(v || v === 0); };
var str_repeat = function(str, times){ return new Array(times + 1).join(str); };
var str_pad = function(self, length, str, dir){
	if (self.length >= length) return this;
	str = str || ' ';
	var pad = str_repeat(str, length - self.length).substr(0, length - self.length);
	if (!dir || dir == 'right') return self + pad;
	if (dir == 'left') return pad + self;
	return pad.substr(0, (pad.length / 2).floor()) + self + pad.substr(0, (pad.length / 2).ceil());
};
//GrowingInput///

});


function ffnamecheck(){
	var ffusername = document.getElementById("ffusername");
	if (ffusername.value.length<1){
		alert("FF Kullanıcı adınızı yazmanız gerekiyor.");
	}
}



	function loginf()
	{
 		//console.log('login');
		$("#loginresult").html("<img src='/images/ind1.gif' border='0'> Lütfen bekleyin..");
		var form = jQuery('#loginform');
		   q = form.formSerialize();
			$.ajax({
				type: "POST",
				url: "/post/login",
				data: q,
				ajaxStart: function() { $("#loginresult").html("Giriş yapılıyor"); },
				success: function(veri) { 
					var errors=new Array();
					veri = Number(veri);
					errors[0]="";
					errors[1]="Böyle bir kullanıcı bulunamadı.";
					errors[2]="Yanlış şifre. BÜYÜK küçük dikkat.";
					errors[3]="Geçerli bir mail girin.";
					errors[4]="Aktifleştirilmemiş hesap.";
					if (veri==0)
					{
						window.location.reload();
					}
					else
					{
					 $("#loginresult").html(errors[veri]);
					}
				},
				dataType: "html"
			  });
		return false;
	}

	function forgotpas()
	{
		mailadd = $("#forgotemail").val();
		if(mailadd!=""){
			$("#forgotresult").html("<img src=\"/images/ind1.gif\" border=\"0\"> Lütfen bekleyin.")
			$("#forgotresult").load("qfuncs.php?ftype=resetpassword&data="+mailadd);
		}else{
			$("#forgotresult").html("Mail adresi girin.")
		}

	return false;
	}

	function signup()
	{
  		//console.log('sign');
		$("#signupresult").html("<img src='/images/ind1.gif' border='0'> Lütfen bekleyin..");
		var form = jQuery('#signupform');
		   q = form.formSerialize();
			$.ajax({
				type: "POST",
				url: "/post/signup",
				data: q,
				ajaxStart: function() { $("#signupresult").html("<img src='/images/ind1.gif' border='0'> Kontrol ediliyor..");},
				success: function(veri) { 
					var errors=new Array();
					errors[0]="";
					errors[1]="Geçersiz kullanıcı adı. <br>[harf rakam altçizgi] min. 4kar.";
					errors[2]="Geçersiz mail adresi.";
					errors[3]="Bu mail ile üye olunmuş.";
					errors[4]="5dk sonra deneyin.";
					errors[5]="Geçersiz kod.";
					errors[6]="Bu kodun kullanımı dolmuş.";
					errors[7]="Bu kullanıcı adı kullanılıyor.";
					//$("#signupresult").html(veri); 
					veri = veri.replace(/^\s+|\s+$/g,"");
					if (IsNumeric(veri)){
						Number(veri);
						veri = errors[veri];
					}
					$("#signupresult").html("<div id='valert'>"+veri+"</div>");
					$("#valert").animate({opacity: 1.0}, 3000).hide('fast');

				},
				dataType: "html"
			  });
		return false;
	}

	function getVideoData(url){
		$("#result").html("Lütfen bekleyin.");

		var RegExp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
		if(RegExp.test(url)){
			$.ajax({
			  url: '/qfuncs.php?ftype=video&data='+$("#url").val(),
			  success: function(data) {
				data = data.split(",");
				$("#title").val(data[0]);
				$("#img").val(data[1]);
				$("#videothumb > img").attr("src",data[1]);
				$("#description").val(data[2]);
				$("#img").focus();
				$("#title").focus();
				$("#result").html("");
			  }
			});
		}else{
			$("#result").html("Hatalı video adresi.");
		}

	/*
	var matches = $('#videoUrl').val().match(/http:\/\/(?:www\.)?youtube.*watch\?v=([a-zA-Z0-9\-_]+)/);
	if (matches) {
		alert('valid');
	} else {
		alert('Invalid');
	}
	*/
	}

function message2user(username){
var tbxcolor;
	if ($('#usertextbox').length) {
		$(".utbinfos").html("<span>Mesaj:</span>");
		$("#usertextbox").focus();
		tbxcolor = $("#usertextbox").css("color");
		$("#usertextbox").animate({color: "#C82F06"}).delay(500).animate({color: tbxcolor});
		$("#usertextbox").val("$"+username+" ");
	} else {
		alert ("Giriş yaptınız mı ?")
	}
}

function add2flist(username,action){
	if(action=="addfriend"){
		okmsg = "Eklendi !";
		quest = " arkadaş listenize eklensin mi?";
	}else{
		okmsg = "Çıkartıldı !"
		quest = " arkadaş listenizden çıkartılsın mı?";
	}
	var p1=confirm(username+quest);
	if(p1){
		$.ajax({
		  url: '/qfuncs.php?ftype='+action+'&data='+username,
		  success: function(data) {
			  if(data=="OK"){
				  alert(okmsg);
				  window.location.reload();
			  }else{
				  alert("Bir sorun oluştu.")
			  }
		  }
		});
	}
}

function go4newpass(){
	var mypass = $("#newpass").val();
	var mail = $("#mailadd").val();

	if(mail.length < 5){
		$("#newpassresult").html("Mail adresinizi girin.");
		return false;
	}

	if(mypass.length < 5){
		$("#newpassresult").html("En az 5 karakterli şifre girin.");
		return false;
	}

	if($("#newpasscheck").val()!=$("#newpass").val()){
		$("#newpassresult").html("Her 2 şifre de aynı olmalıdır.");
		return false
	}

}

function gototab(){
   $("html:not(:animated),body:not(:animated)").animate({ scrollTop: 0}, 500 );
   collapser();
   return false;
}

function checkin(eid,defval){
	var elem = $("#"+eid).val();
	if(elem=="" || elem==defval){
		return false;
	}
}

function saveDraft(){
	var title = $("#title").attr("value");
	var content = $("#contentarea").attr("value");
	
	localStorage.setItem('htitle', title);
	localStorage.setItem('hcontent', content);
	console.log("Taslak kayıt edildi.");
}
	
function loadDraft(){
	var storage = window['localStorage'];
	if (!window['localStorage']) return;

	if (storage.getItem('htitle')) {
		var title = storage.getItem('htitle');
		var content = storage.getItem('hcontent');
		
		$("#title").attr("value",title);
		$("#contentarea").attr("value",content);
		console.log("Taslak yüklendi.");

	} else {
		alert("Önceden kayıt edilmiş bir taslağınız yok.");
		console.log("Taslak bulunamadı.");

	}
	
}


var collapsed
function collapser(){
	if($('.collapse').height()==195){
		$(".collapse").animate({
			height : '0'
		},function(){
                                            $(".collapse").hide()
                                        });
		
	}else{
                                        $(".collapse").show();
		$(".collapse").animate({
			height : '195'
		})
		
	}
}
