var LOGIN_USERNAME = 'username';
var LOGIN_PASSWORD = 'password';
var SEARCH_DEFAULT = 'Find your domains';
var GLOBAL_SEARCH_DEFAULT = 'quick search...';

//function used to test if value is an integer, returns true if is, false if not
function is_int(value){
	if((parseFloat(value) == parseInt(value)) && !isNaN(parseInt(value))){
		return true;
	} else {
		return false;
	}
}

// caplitalize all words of a string
String.prototype.capitalize = function(){
	return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};

function checkSessionStatus(){
	$.ajax({
		type: 'POST',
		url: CHECK_SESSION_URL,
		dataType: 'json',
		success: function(data){
			if(data.status == false){
				alert("Your session has expired, please log back in");
				window.location = window.location;
			}
		}
	});
}

// global iframe overlay window
var iframeOverlayWindow = null;


function resizeIframeOverlay(width, height, animationSpeed, callback){

    // Use existing left and top
  	t = $('#iframe_modal_window', window.parent.document).css('top');
   	l = $('#iframe_modal_window', window.parent.document).css('left')
        
	$('#iframe_modal_window iframe', window.parent.document).css('min-height', height);
	$('#iframe_modal_window', window.parent.document).css('height', height);
    
    $('#iframe_modal_window', window.parent.document).animate({
    	left: l,
    	top: t,
    	width: width,
    	height: height
    }, animationSpeed , function(){
    	if(callback != null){
    		callback();
    	}
    	
    });
}



// display iframe overlay
function displayIframeOverlay(url, width, height, topSpace){

	$('#iframe_modal_window .overlay_inner_content').hide();
	$('#iframe_modal_window .overlay_inner_content').html('');
	$('#iframe_modal_window').css('width', width);
	$('#iframe_modal_window').css('height', height);

	$('#iframe_modal_window .overlay_content').css('height', $('#iframe_modal_window .overlay_c').css('height'));	
	$('#iframe_modal_window .overlay_loading').css('height', height);	
	
	$('#iframe_modal_window .overlay_loading').show();
	$('#iframe_modal_window iframe').hide();
	$('#iframe_modal_window iframe').css('min-height', height);
	
	if (topSpace == null) {
		topSpace = '25%';
	}

	if(iframeOverlayWindow == null){
	
		iframeOverlayWindow = $('#iframe_modal_window').overlay({
			mask: {
				color: '#000',
				opacity: 0.6,
				loadSpeed: 1
			},
			closeOnClick: false,
			load: false,
			top: topSpace,
			speed: 0
		});
	}

	iframeOverlayWindow.overlay().load();

	$('#iframe_modal_window iframe').src(url,
	
		function(iframe, duration){
			$('#iframe_modal_window .overlay_loading').hide();
			$('#iframe_modal_window iframe').show();
		}
	);
	
	$('#iframe_modal_window iframe').load(function(){
		$('#iframe_modal_window iframe').contents().find('.close_overlay').bind('click', function(){
			$('#iframe_modal_window iframe').contents().find('body').html('');
			$('#iframe_modal_window .overlay_loading').show();
			iframeOverlayWindow.overlay().close();
		});		
	});
}

function displayConfirmationOverlay(message, yesCallback){

	var width = '375px';
	var height = '100px';
	
	$('#iframe_modal_window iframe').hide();
	$('#iframe_modal_window').css('width', width);
	$('#iframe_modal_window').css('height', height);
	$('#iframe_modal_window .overlay_loading').hide();
	$('#iframe_modal_window .overlay_content').css('height', $('#iframe_modal_window .overlay_c').css('height'));
	$('#iframe_modal_window .overlay_inner_content').css('height', $('#iframe_modal_window .overlay_c').css('height'));
	$('#iframe_modal_window .overlay_inner_content').css('min-height', height);
	$('#iframe_modal_window .overlay_inner_content').show();

	var messageHtml = '';
	
	messageHtml	   += '<div class=\"confirmation_fieldset\"><h1>Wait! Are you sure?</h1>';
	messageHtml    += '<div class=\"overlay_confirmation_message\">' + message + '</div>';
	messageHtml    += '<div class=\"overlay_confirmation_buttons\"><input type=\"button\" value=\"confirm\" id=\"overlay_confirm\" class=\"rounded_button button_blue button_20\" />';
	messageHtml    += '&nbsp;&nbsp;<input type=\"button\" value=\"cancel\" id=\"overlay_confirm_cancel\" class=\"rounded_button button_orange button_20\"/>';
	messageHtml    += '</div>';
	messageHtml    += '</div>';
	
	$('#iframe_modal_window .overlay_inner_content').html(messageHtml);

	if(iframeOverlayWindow == null){
		
		iframeOverlayWindow = $('#iframe_modal_window').overlay({
			mask: {
				color: '#000',
				opacity: 0.6,
				loadSpeed: 1
			},
			closeOnClick: false,
			load: false,
			top: '25%',
			speed: 0
		});
	}

	iframeOverlayWindow.overlay().load();

	$('#iframe_modal_window #overlay_confirm').click(function(){
		iframeOverlayWindow.overlay().close();
		yesCallback();
	});
	
	$('#iframe_modal_window #overlay_confirm_cancel').click(function(){
		iframeOverlayWindow.overlay().close();
	});
}
	
function displayModalAlert(title, message, width, height){
	
	$('#iframe_modal_window iframe').hide();
	$('#iframe_modal_window').css('width', width);
	$('#iframe_modal_window').css('height', height);
	$('#iframe_modal_window .overlay_loading').hide();
	$('#iframe_modal_window .overlay_content').css('height', $('#iframe_modal_window .overlay_c').css('height'));
	$('#iframe_modal_window .overlay_inner_content').css('height', $('#iframe_modal_window .overlay_c').css('height'));
	$('#iframe_modal_window .overlay_inner_content').css('min-height', height);
	$('#iframe_modal_window .overlay_inner_content').show();
	//$('#iframe_modal_window .confirmation_fieldset').height($('#iframe_modal_window .overlay_c').height());
	
	var messageHtml = '';
	
	messageHtml	   += '<div class=\"confirmation_fieldset\"><h1>' + title + '</h1>';
	messageHtml    += '<div class=\"overlay_confirmation_message\">' + message + '</div>';
	messageHtml    += '<div class=\"overlay_confirmation_buttons\">';
	messageHtml    += '<input type=\"button\" value=\"close\" id=\"overlay_confirm_cancel\" class=\"rounded_button button_orange button_20\"/>';
	messageHtml    += '</div>';
	messageHtml    += '</div>';

	$('#iframe_modal_window .overlay_inner_content').html(messageHtml);

	if(iframeOverlayWindow == null){
		
		iframeOverlayWindow = $('#iframe_modal_window').overlay({
			mask: {
				color: '#000',
				opacity: 0.6,
				loadSpeed: 1
			},
			closeOnClick: false,
			load: false,
			top: '25%',
			speed: 0
		});
	}

	iframeOverlayWindow.overlay().load();

	$('#iframe_modal_window #overlay_confirm_cancel').click(function(){
		iframeOverlayWindow.overlay().close();
	});
}
		
		
// close overlay from iframe
function closeParentWindow(){
	iframeOverlayWindow.overlay().close();
}





function blockbox(id, message){
	if(message == null) {
		message = '<span class="loading_display">&nbsp;</span>';
		$('#'+id).block({
			message: message,
			css: {
				backgroundColor: 'transparent',
				border: 'none',
				width: '20px'
			},
			overlayCSS: {
				backgroundColor: '#CCC',
				opacity: 0.5
			}
		});	
	} else {	
		$('#'+id).block({
			message: '<h3>' + message + '</h3>',
			overlayCSS: { 
				backgroundColor: '#CCC'
			}
		});	
	}
}

function highlightRow(row){
	if($(row).parent().parent().hasClass('checked') )
		$(row).parent().parent().removeClass('checked');
	else
		$(row).parent().parent().addClass('checked');
}

function disableSelection(target){
	if (typeof target.onselectstart!="undefined") //IE route
		target.onselectstart=function(){return false}
	else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
		target.style.MozUserSelect="none"
	else //All other route (ie: Opera)
		target.onmousedown=function(){return false}
	target.style.cursor = "default"
}

/**
 * Add commas to format a number
 * @param nStr
 * @return
 */
function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

/*
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};


/**
 * Remove an item from an array
 * @param array
 * @param item
 * @return
 */
function removeItems(array, item) {
	var i = 0;
	while (i < array.length) {
		if (array[i] == item) {
			array.splice(i, 1);
		} else {
			i++;
		}
	}
	return array;
}

 
 function creditCardTypeFromNumber(number) {

     var re = new RegExp("^4");
     if (number.match(re) != null)
         return "VISA";

     re = new RegExp("^(34|37)");
     if (number.match(re) != null)
         return "AMERICAN_EXPRESS";

     re = new RegExp("^5[1-5]");
     if (number.match(re) != null)
         return "MASTERCARD";

     re = new RegExp("^6011");
     if (number.match(re) != null)
         return "DISCOVER";
}
 
function reloadUserInfoHeader(){
	$('#user_info_header').load(USER_INFO_HEADER_URL);
}

/**
 * Find all the checked checkboxes in a DOM node
 * and convert the checked ids into a string
 * 
 * Example: 1|2|3|4
 */
jQuery.fn.parseCheckboxIds = function() {

    var o = $(this);
	var ids = new Array();
	
	$('input:checked', o).each(function(i) {
            ids.push(this.name.match(/\d+/g));
    });

    ids = ids.join('|');
    return ids;
};

jQuery.fn.limitInputToNumbers = function(){
	
	$(this).change(function(){
		$(this).val($(this).val().replace(/[^0-9]/g, ''));
	});
}

jQuery.fn.applyAllForm = function(selector){
	
	table = this;
	
	els = $(selector).find(':input');

	els.each(function(){
		
		element = this;
	
		elementClass = element.className;

		if(this.className != null){
			
			switch(element.type || element.tagName){
			

				case "text":
					
					$(element).keyup(function(){
						
						inputEls = $(table).find('.' + this.className);
						
						val = $(this).val();

						inputEls.each(function(){
							$(this).val(val);
						});
					});
					
					break;
				
				case "checkbox":
					
					$(element).click(function(){
						inputEls = $(table).find('.' + this.className);
						
						isChecked = $(this).is(":checked");
						
						inputEls.each(function(){
							$(this).attr('checked', isChecked);
						});
					});
					
					break;
					
				case "select-one":
					
					$(element).change(function(){
						inputEls = $(table).find('.' + this.className);
						
						val = $(this).val();

						inputEls.each(function(){
							$(this).val(val);
						});
					});
					
					break;
					
				case "radio":

					$(element).click(function(){
						
						inputEls = $(table).find("input:radio");

						val = $(this).val();
						
						inputEls.each(function(){
							if($(this).val() == val){
								$(this).attr('checked', true);
							} else {
								$(this).attr('checked', false);
							}
						});
						
					});
					
					
					break;
					
				default:
					break;
				}
		}
	});
}





if($.fn.dataTableExt){
	$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback )
	{
		if ( typeof sNewSource != 'undefined' )
		{
			oSettings.sAjaxSource = sNewSource;
		}
		
		oSettings.bServerSide = true;
		
		this.oApi._fnProcessingDisplay( oSettings, true );
		var that = this;
	
		oSettings.fnServerData( oSettings.sAjaxSource, null, function(json) {
	
			/* Clear the old information from the table */
			that.oApi._fnClearTable( oSettings );
			
			/* Got the data - add it to the table */
			for ( var i=0 ; i<json.aaData.length ; i++ )
			{
				that.oApi._fnAddData( oSettings, json.aaData[i] );
			}
	
			oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
			that.fnDraw( that );
			
			that.oApi._fnProcessingDisplay( oSettings, false );
		
			/* Callback user function - for event handlers etc */
			if ( typeof fnCallback == 'function' )
			{
				fnCallback( oSettings );
			}
		} );
	}
}



jQuery.fn.populate = function(obj, options) {
	
	
	// ------------------------------------------------------------------------------------------
	// JSON conversion function
	
		// convert 
			function parseJSON(obj, path)
			{
				// prepare
					path = path || '';
				
				// iteration (objects / arrays)
					if(obj == undefined)
					{
						// do nothing
					}
					else if(obj.constructor == Object)
					{
						for(var prop in obj)
						{
							var name	= path + (path == '' ? prop : '[' +prop+ ']');
							parseJSON(obj[prop], name);
						}
					}
						
					else if(obj.constructor == Array)
					{
						for(var i = 0; i < obj.length; i++)
						{
							var index	= options.useIndices ? i : '';
							index		= options.phpNaming ? '[' +index+']' : index;
							var name	= path + index;
							parseJSON(obj[i], name);
						}
					}
					
				// assignment (values)
					else
					{
						// if the element name hasn't yet been defined, create it as a single value
						if(arr[path] == undefined)
						{
							arr[path] = obj;
						}
		
						// if the element name HAS been defined, but it's a single value, convert to an array and add the new value
						else if(arr[path].constructor != Array)
						{
							arr[path] = [arr[path], obj];
						}
							
						// if the element name HAS been defined, and is already an array, push the single value on the end of the stack
						else
						{
							arr[path].push(obj);
						}
					}
	
			};


	// ------------------------------------------------------------------------------------------
	// population functions
		
		function debug(str)
		{
			if(window.console && console.log)
			{
				console.log(str);
			}
		}
		
		function getElementName(name)
		{
			if (!options.phpNaming)
			{
				name = name.replace(/\[\]$/,'');
			}
			return name;
		}
		
		function populateElement(parentElement, name, value)
		{
			var selector	= options.identifier == 'id' ? '#' + name : '[' +options.identifier+ '="' +name+ '"]';
			var element		= jQuery(selector, parentElement);
			value			= value.toString();
			value			= value == 'null' ? '' : value;
			element.html(value);
		}
		
		function populateFormElement(form, name, value)
		{

			// check that the named element exists in the form
				var name	= getElementName(name); // handle non-php naming
				var element	= form[name];
				
			// if the form element doesn't exist, check if there is a tag with that id
				if(element == undefined)
				{
					// look for the element
						element = jQuery('#' + name, form);
						if(element)
						{
							element.html(value);
							return true;
						}
					
					// nope, so exit
						if(options.debug)
						{
							debug('No such element as ' + name);
						}
						return false;
				}
					
			// debug options				
				if(options.debug)
				{
					_populate.elements.push(element);
				}
				
			// now, place any single elements in an array.
			// this is so that the next bit of code (a loop) can treat them the 
			// same as any array-elements passed, ie radiobutton or checkox arrays,
			// and the code will just work

				elements = element.type == undefined && element.length ? element : [element];
				
				
			// populate the element correctly
			
				for(var e = 0; e < elements.length; e++)
				{
					
				// grab the element
					var element = elements[e];
					
				// skip undefined elements or function objects (IE only)
					if(!element || typeof element == 'undefined' || typeof element == 'function')
					{
						continue;
					}
					
				// anything else, process
					switch(element.type || element.tagName)
					{
	
						case 'radio':
							// use the single value to check the radio button
							element.checked = (element.value != '' && value.toString() == element.value);
							
						case 'checkbox':
							// depends on the value.
							// if it's an array, perform a sub loop
							// if it's a value, just do the check
							
							var values = value.constructor == Array ? value : [value];
							for(var j = 0; j < values.length; j++)
							{
								element.checked |= element.value == values[j];
							}
							
							//element.checked = (element.value != '' && value.toString().toLowerCase() == element.value.toLowerCase());
							break;
							
						case 'select-multiple':
							var values = value.constructor == Array ? value : [value];
							for(var i = 0; i < element.options.length; i++)
							{
								for(var j = 0; j < values.length; j++)
								{
									element.options[i].selected |= element.options[i].value == values[j];
								}
							}
							break;
						
						case 'select':
						case 'select-one':
							element.value = value.toString() || value;
							break;
	
						case 'text':
						case 'button':
						case 'textarea':
						case 'submit':
						default:
							value			= value == null ? '' : value;
							element.value	= value;
							
					}
						
				}

		}
		

		
	// ------------------------------------------------------------------------------------------
	// options & setup
		
		// exit if no data object supplied
			if (obj === undefined)
			{
				return this;
			};
		
		// options
			var options = jQuery.extend
			(
				{
					phpNaming:			true,
					phpIndices:			false,
					resetForm:			true,
					identifier:			'id',
					debug:				false
				},
				options
			);
				
			if(options.phpIndices)
			{
				options.phpNaming = true;
			}
	
	// ------------------------------------------------------------------------------------------
	// convert hierarchical JSON to flat array
		
			var arr	= [];
			parseJSON(obj);
			
			if(options.debug)
			{
				_populate =
				{
					arr:		arr,
					obj:		obj,
					elements:	[]
				}
			}
	
	// ------------------------------------------------------------------------------------------
	// main process function
		
		this.each
		(
			function()
			{
				
				// variables
					var tagName	= this.tagName.toLowerCase();
					var method	= tagName == 'form' ? populateFormElement : populateElement;
					
				// reset form?
					if(tagName == 'form' && options.resetForm)
					{
						this.reset();
					}

				// update elements
					for(var i in arr)
					{
						method(this, i, arr[i]);
					}
			}
			
		);

return this;
};


/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

function getURLVariables() {
	
	// If no elemets are passed use the window object
	if (getURLVariables.arguments.length == 1) element = getURLVariables.arguments[0];
	else element = window;
	
	var vars = [];	
	var hashes = element.location.href.slice(element.location.href.indexOf('?') + 1).split('&');
	for(var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	
	return vars;
}

/**
 * Signup dropdown class
 */
var SignupDropDown = {
	numSeconds:       5,
	cookieName:       'signup_form_displayed',
	isDisplayedValue: 'displayed',
	element:          '#signup-dropdown',
	
	init: function(){
		if(!parent.window['IS_LOGGED_IN']){
			if(!this.hasBeenDisplayed()){
				this.startTimer();
			}
		}
	},
	
	addCloseListener: function(){
		var that = this;
		
		$(this.element).find('.close').click(function(){
			$(that.element).css('top', -204);
			return false;
		});
	},
	
	startTimer: function(){
		var that = this;
		this.startTime = new Date().getTime();
		
		this.currentTimeout = setTimeout(function(){
			that.showSignupForm();
		}, this.numSeconds * 1000);
	},
	
	addClickListener: function(){
		var that = this;
		
		$('a').click(function(){
			if(that.findPreviousTimeout() != that.isDisplayedValue){
				that.storeCurrentTimeout();
			}
		});
	},
	
	storeCookie: function(){
		$.cookie(this.cookieName, this.isDisplayedValue);
	},
	
	hasBeenDisplayed: function(){
		var cookieVal = $.cookie(this.cookieName);
		if(cookieVal == this.isDisplayedValue){
			return true;
		}
		return false;
	},

	showSignupForm: function(){
		var that = this;
		this.addCloseListener();
		
		this.storeCookie();
		$(this.element).css('left', this.getLeftDropdownPosition());
		$(this.element).animate( {top: this.getPageTop()}, 1500, 'easeInElastic');
		
		$(window).scroll(function() {
			that.scrollAction();
		});
	},
	
	scrollAction: function() {
		$(this.element).css('top', this.getPageTop());
	},
	
	getPageTop: function() {
		return (window.pageYOffset != undefined) ? window.pageYOffset : document.documentElement.scrollTop;
	},
	
	getLeftDropdownPosition: function() {
		if (document.body && document.body.offsetWidth) {
			windowWidth = document.body.offsetWidth;
		}
		else if(document.compatMode=='CSS1Compat' && document.documentElement && document.documentElement.offsetWidth ) {
			windowWidth = document.documentElement.offsetWidth;
		}
		else if (window.innerWidth && window.innerHeight) {
			windowWidth = window.innerWidth;
		}

		multiplier = $(window).width() - parseInt($("#signup-dropdown").css('width'));
		return (Math.floor(Math.random() * multiplier));
	}
};


/**
 * Plugin to perform ajax validation on an entire form
 * 
 * Url parameter is the url where plugin should submit the 
 * form to for validation.
 * 
 * This plugin will return true or false depending on if
 * the form was valid or not.
 */
(function($) {
	
	var formStatus = false;
	
	$.fn.ajaxValidate = function(url){

		form = this;
		
		var params = $(form).serialize();
		
		$.ajax({
			type: 'POST',
			dataType: 'json',
			success: processFormResponse,
			url: url,
			data: params,
			cache: false,
			async: false
		});

		return formStatus;
	};

	function processFormResponse(data){
		$('.error').remove();
		if(data.status == 'invalid'){
			removeOldErrors();
			renderErrors(data.errors);
			formStatus = false;
		} else {
			formStatus = true;
		}
		return false;
	};
	
	function removeOldErrors(){
		$('.error_field_wrapper').children().unwrap();
	}
	
	function renderErrors(errors){
		for(var i=0; i<errors.length; i++){
			addErrorToField(errors[i].field, errors[i].error);
		}
	};
	
	function addErrorToField(field, error){
		$('#' + field).parent().parent().find('.form_help').remove();
		$('#' + field).wrap('<div class=\"error_field_wrapper\" />');
		$('#' + field).after('<span class=\"error\">' + error + '</span>');
		//$('#' + field).after('<span class=\"error\">&nbsp;</span>');
	};
	
})(jQuery);

//this only for sign up validate
(function($) {
	
	var formStatus = false;
	
	$.fn.ajaxSignupValidate = function(url){

		form = this;
		
		var params = $(form).serialize();
		
		$.ajax({
			type: 'POST',
			dataType: 'json',
			success: processFormResponse,
			url: url,
			data: params,
			cache: false,
			async: false
		});

		return formStatus;
	};

	function processFormResponse(data){
		$('span.field_status_error').remove();
		$('.error_field_input').removeClass('error_field_input');

		if(data.status == 'invalid'){
			//removeOldErrors();
			renderErrors(data.errors);
			formStatus = false;
		} else {
			formStatus = true;
		}
		return false;
	};
	
	function removeOldErrors(){
		$('.error_field_wrapper').children().unwrap();
	}
	
	function renderErrors(errors){
		for(var i=0; i<errors.length; i++){
			addErrorToField(errors[i].field, errors[i].error);
		}
	};
	
	function addErrorToField(field, error){
		$('#' + field).addClass('error_field_input');
		$('#' + field).after('<span class=\"field_status_error\">' + error + '</span>');
	};
	
})(jQuery);

(function($) {

	  var timer;

	  $.fn.src = function(url, onLoad, options) {
	    setIFrames($(this), onLoad, options, function() {
	      this.src = url;
	    });
	    return $(this);
	  }

	  $.fn.squirt = function(content, onLoad, options) {

	    setIFrames($(this), onLoad, options, function() {
	      var doc = this.contentDocument || this.contentWindow.document;
	      doc.open();
	      doc.writeln(content);
	      doc.close();
	    });
	    return this;

	  }

	  function setIFrames(iframes, onLoad, options, iFrameSetter) {
	    iframes.each(function() {
	      if (this.tagName=="IFRAME") setIFrame(this, onLoad, options, iFrameSetter);
	    });
	  }

	  function setIFrame(iframe, onLoad, options, iFrameSetter) {

	    var iframe;
	    iframe.onload = null;
	    if (timer) clearTimeout(timer);

	    var defaults = {
	      timeoutDuration: 0,
	      timeout: null
	    }
	    var opts = $.extend(defaults, options);
	    if (opts.timeout && !opts.timeoutDuration) opts.timeoutDuration = 60000;

	    opts.frameactive = true;
	    var startTime = (new Date()).getTime();
	    if (opts.timeout) {
	      var timer = setTimeout(function() {
	        opts.frameactive=false; 
	        iframe.onload=null;
	        if (opts.timeout) opts.timeout(iframe, opts.timeout);
	      }, opts.timeoutDuration);
	    };

	    var onloadHandler = function() {
	      var duration=(new Date()).getTime()-startTime;
	      if (timer) clearTimeout(timer);
	      if (onLoad && opts.frameactive) onLoad.apply(iframe,[duration]);
	      opts.frameactive=false;
	    }
	    iFrameSetter.apply(iframe);
	    iframe.onload = onloadHandler;
	    opts.completeReadyStateChanges=0;
	    iframe.onreadystatechange = function() { // IE ftw
		    if (++(opts.completeReadyStateChanges)==3) onloadHandler();
	    }

	    return iframe;

	  };

	})(jQuery);

	function findSWF(movieName) {
	  if (navigator.appName.indexOf("Microsoft")!= -1) {
	    return window[movieName];
	  } else {
	    return document[movieName];
	  }
	}

$(document).ready(function(){

	$('.dataTable tr').live('mouseover mouseout', function(event) {
		
		  if (event.type == 'mouseover') {
			  $(this).addClass("over");
		  } else {
			  $(this).removeClass("over");
		  }
		});
	
	
	// add table striping to all tables with the class: tableClass
	$("table.standardTable > tbody > tr:odd").addClass("alt");
	
	$("table.standardTable > tbody tr.rowHasErrors:odd").addClass("otherErrors");

	$("table.standardTable > tbody > tr").hover(
			function(){
				$(this).addClass("over");
			},
			function(){
				$(this).removeClass("over");
			}
	)
	
	$('#quick_search_input').val(GLOBAL_SEARCH_DEFAULT).click(function(){
		$(this).val("");
	});
	$('#quick_search_input').blur(function(){
		if($(this).val() == ""){
			$(this).val(GLOBAL_SEARCH_DEFAULT);
		}
	});
	
	$('#search_bullet #search').val(SEARCH_DEFAULT).click(function(){
		$(this).val("");
	});
	$('#search_bullet #search').blur(function(){
		if($(this).val() == ""){
			$(this).val(SEARCH_DEFAULT);
		}
	});
	

	
	$("#signin_username").val(LOGIN_USERNAME).click(function(){
		$(this).val("");
	});

	$("#signin_username").blur(function(){
		if($(this).val() == ""){
			$(this).val(LOGIN_USERNAME);
		}
	});
	
	var passwordField = $('#signin_password');
	
	passwordField.after('<input id="passwordPlaceholder" type="text" value="password" />');
	var passwordPlaceholder = $('#passwordPlaceholder');
	
	passwordPlaceholder.show();
	passwordField.hide();
	
    // when focus is placed on the placeholder hide the placeholder and show the actual password field
    passwordPlaceholder.focus(function() {
        passwordPlaceholder.hide();
        passwordField.show();
        passwordField.focus();
    });
    // and vice versa: hide the actual password field if no password has yet been entered
    passwordField.blur(function() {
        if(passwordField.val() == '') {
            passwordPlaceholder.show();
            passwordField.hide();
        }
    });
    
    $('.holding input').each(function(){
    	if($(this).val() != ""){
    		$(this).parent().find('.holder').hide();
    	}
    });
    
    $('.holding input[type=text], .holding input[type=password]').bind('keyup blur', function(){
    	
    	$(this).parent().find('.holder').removeClass('focused');
    	
    	if($(this).val() !== ""){
    		$(this).parent().find('.holder').hide();
    	} else {
    		$(this).parent().find('.holder').show();
    		$(this).parent().find('.holder').css('display', 'inline');
    	}
    });
    
    $('.holder').click(function(){
    	$(this).addClass('focused');
    	$(this).parent().find('input').focus();
    });
    
    $('.holding > input').focus(function(){
    	$(this).parent().find('.holder').addClass('focused');
    });
   
    // Store the URL for for later processing.
    $("a.othernetworkstoreurl").click(function() {
    	
    	if (parent.window.iframeOverlayWindow) {
    		var targetURL = parent.window.location.href;
    		var loadPopup = true;
    	}
    	else {
    		var targetURL = window.location.href;
    		var loadPopup = false;
    	}
    	
    	$.ajax({
			async: false,
			type: 'POST',
			url: OTHER_NETWORK_LOGIN_REDIRECT_URL,
			data: {loginURL: targetURL, loadPopup: loadPopup},
			dataType: 'json'
		});

    	if (loadPopup) {
    		parent.window.location = $(this).attr('href'); 
    		return false;
    	}
    	
    	return true;
	});

    
});

//NAV ANIMATION & IE HOVER FIX ////////////////////////////////////////////
$(document).ready(function(){
	$("#nav_normal li ul").hide();	
	$("#nav_normal li").hover(
			
		function(){ $("ul", this).show();
					thisid = $(this).attr("id");
					$(this).attr({id: thisid + "_over"});
				}, 
		function() { $("ul", this).hide();
					thisid = $(this).attr("id").replace("_over", "");
					$(this).attr({id: thisid});
				}
	);
	
	if (document.all) {
		$(".nav li, .nav_logged_in li").mouseover(
			function() {$(this).addClass("over");},
			function() {$(this).removeClass("over");}
		);
		$(".nav li, .nav_logged_in li").mouseout(
			function() {}
			//setTimeout("function() {$(this).removeClass('over')}", 1000);
		);			
	}
	
	$('.home_listings_table tr td').click(function(){
		url = $(this).parent().find('a').attr('href');
		window.location = url;
	});

	$("div.home_listings div.home_listing_row:even").addClass("alt");

	$(".nav-item").hover(function() {
		$(this).addClass('nav-item-over');
		$(this).removeClass('nav-item');
		
	}, function() {
		$(this).addClass('nav-item');
		$(this).removeClass('nav-item-over');
	});

	SignupDropDown.init();
});


function ucwords (str) {
    // Uppercase the first character of every word in a string  
    // 
    // version: 1107.2516
    // discuss at: http://phpjs.org/functions/ucwords    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Waldo Malqui Silva
    // +   bugfixed by: Onno Marsman
    // +   improved by: Robin
    // +      input by: James (http://www.james-bell.co.uk/)    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: ucwords('kevin van  zonneveld');
    // *     returns 1: 'Kevin Van  Zonneveld'
    // *     example 2: ucwords('HELLO WORLD');
    // *     returns 2: 'HELLO WORLD'    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
	return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
        return $1.toUpperCase();
    });
}







