self.gg = {
	countryCode : '',
	stateCode : ''
};

function setCookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires ) {
	expires = expires * 1000 * 60 * 60 * 24;
	}
	
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function storeTimezone() {
	var now = new Date();
		
	// Set cookie for the time zone offset in minutes
	setCookie("time_zone_offset", now.getTimezoneOffset(), 365, "/"); 
	
	// Create two new dates
	var d1 = new Date();
	var d2 = new Date(); 
	
	// Date one is set to January 1st of this year
	// Guaranteed not to be in DST for northern hemisphere,
	// and guaranteed to be in DST for southern hemisphere
	// (If DST exists on client PC)
	d1.setDate(1);
	d1.setMonth(1); 
	
	// Date two is set to July 1st of this year
	// Guaranteed to be in DST for northern hemisphere,
	// and guaranteed not to be in DST for southern hemisphere
	// (If DST exists on client PC)
	d2.setDate(1);
	d2.setMonth(7); 
	
	// If time zone offsets match, no DST exists for this time zone
	if (parseInt(d1.getTimezoneOffset(), 10) == parseInt(d2.getTimezoneOffset(), 10)) {
		setCookie("time_zone_dst", "0", 365, "/", ".reshapethenation.com");
	} else { // DST exists for this time zone - check if it is currently active
		// Find out if we are on northern or southern hemisphere
		// Hemisphere is positive for northern, and negative for southern
		var hemisphere = parseInt(d1.getTimezoneOffset(), 10) - parseInt(d2.getTimezoneOffset(), 10); 
		
		// Current date is still before or after DST, not containing DST
		if ((hemisphere > 0 && parseInt(d1.getTimezoneOffset(), 10) == parseInt(now.getTimezoneOffset(), 10)) || (hemisphere < 0 && parseInt(d2.getTimezoneOffset(), 10) == parseInt(now.getTimezoneOffset(), 10))) {
			setCookie("time_zone_dst", "0", 365, "/", ".reshapethenation.com");
		} else { // DST is active right now with the current date 
		 	setCookie("time_zone_dst", "0", 365, "/", ".reshapethenation.com");
		} 
	}
}	

function parentRedirect() {
	window.parent.location.reload();
}

function resize(newWidth, newHeight, alterHeight) {
	var browserHeight = jQuery(window).height();
	var browserWidth = jQuery(window).width();
	
	if (alterHeight) {
		if (browserHeight > 700) {
			newHeight = alterHeight;
		}
	}
		
	var newWidthMargin = -(newWidth/2);
	var newHeightMargin = -(newHeight/2);

	jQuery('#TB_window').css({
		'width': newWidth,
		'margin-left': newWidthMargin,
		'margin-top': newHeightMargin
	});
	jQuery('#TB_iframeContent').css({
		'width': newWidth-1,
		'height': newHeight
	});
};

function addFriend(UserID,FriendID) {
	alert("The script to add FriendID " + FriendID + " to the friends list of " + UserID + " would be performed here.");
	jQuery('#popBox').css('display', 'none');	
};

function blockUser(UserID,FriendID) {
	alert("The script to Block User " + FriendID + " to the friends list of " + UserID + " would be performed here.");
	jQuery('#popBox2').css('display', 'none');	
};

function pop(URL,width,height) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width="+width+",height="+height+"');");
};

function popUp(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=600,height=200,left = 490,top = 300');");
};

function add_stat(url){
	jQuery.post(url, { type: "stats"}, function(data){});    
};

function set_st(value, my_type) {
	if (my_type == "AccountType") {
		jQuery.post("/json/set/f/SignupType/", { type: value },function(data){});
		if (value == "SugarDaddy") {
			jQuery('#LookingForBaby').attr('selected', 'selected');	
		} else {
			jQuery('#LookingForDaddy').attr('selected', 'selected');	
		}
	} else if (my_type == "LookingForType") {
		if (value == "SugarDaddy") {
			jQuery('#AccountTypeBaby').attr('selected', 'selected');	
		} else {
			jQuery('#AccountTypeDaddy').attr('selected', 'selected');	
		}
	} else {
		jQuery.post("/json/set/f/SignupType/", { type: value },function(data){});
	}	   
};

function set_state(value) {
	jQuery.post("/ajax/", {type:value}, function(data){
		jQuery('#StateCode').html(data);
	});
};

function capitalize_word(loc) {
	loc = loc.toLowerCase();
	var Rx= /\b([a-z]+)\b/ig;
	loc = loc.replace(Rx,function(w){
		return w.charAt(0).toUpperCase()+w.substring(1);
	});
	return loc;
};

function get_geo() {
	jQuery.ajax({
		url: "/json/getgeo/", 
		async: false,
		dataType: 'json',
		success: function(data){
			gg.countryCode = data.COUNTRY_CODE;
			gg.stateCode = data.STATE_CODE;
			var loc = capitalize_word(data.CITY)+", "+data.STATE_CODE;
			if (jQuery('#location')) {
				jQuery('#location').html('in '+loc);
			}
		}
	});
};

function get_region() {
	jQuery.getJSON("/json/getgeo/", function(data){
		var loc = capitalize_word(data.CITY+", "+data.REGION);
    });
};

function get_search(gender, thumbCount, showLogin, countryCode, stateCode) {
	if (thumbCount === null) {
		thumbCount = 0;
	}
	if (gender === null) {
		gender = "SugarBaby";
	}
	var container = jQuery('#thumbs-container');
	var clearList = jQuery('<div class="clear"></div>');
	container.empty();
	jQuery.ajax({
		url: "/json/getsearch/",
		async: false,
		data: {'st': gender, 'le': thumbCount, 'hi': 1, 'cc': countryCode, 'sc': stateCode},
		dataType: 'json',
		success: function(data){
			jQuery.each(data, function(i,item) {
				var info = item.DisplayName+", "+item.Age;
				var thumbClass;
				if (i == thumbCount-1) {
					thumbClass = 'thumbs thumbs-end';
				} else {
					thumbClass = 'thumbs';
				}
				var thumb = jQuery('<div>').attr({
					'id': 'thumb'+i,
					'class': thumbClass
				});
				
				var thumbi = jQuery('<img>').attr({
					'src': item.DefaultPicture,
					'alt': item.DisplayName,
					'width': 80,
					'height': 80	
				});
				
				if (showLogin) {
					var imagea = jQuery('<a>').attr('href', '/search/profile/member/'+item.SeoLink);
					imagea.append(thumbi);
					thumb.append(imagea);
				} else {
					thumb.append(thumbi);
				}
				thumb.append(jQuery('<div>').attr({
					'id': 'thumb'+i+'-info',
					'class': 'thumb-info'
				}).html(info));
				if (showLogin) {
					thumb.append(jQuery('<div>').attr({
						'id': 'thumb'+i+'-login',
						'class': 'thumb-login'
					}).html(item.DisplayLastLogin+' ago'));
				}
				container.append(thumb);
			});
			container.append(clearList);
		}
	});
};

function set_gender(gender) {
	if (gender == "SugarDaddy") {
		gender = "Sugar Daddies";
	} else {
		gender = "Sugar Babies";
	}
	jQuery('#location-gender').html(gender);	
};

function close_redirect() {
	//thickbox close
	tb_remove();
	window.location = "http://"+location.host+"/login/";
};

function run_index(gender, thumbCount) {
	get_geo();
	get_search(gender, thumbCount, false, gg.countryCode, gg.stateCode);
};

function run_results(gender, thumbCount, countryCode, stateCode) {
	get_search(gender, thumbCount, true, countryCode, stateCode);
	get_region();
};

function set_status(value, my_type, thumbCount) {
	var gender;
	if (value == "SugarDaddy") {
		gender = "SugarBaby";
	} else {
		gender = "SugarDaddy";
	}
	get_geo();
	set_st(value, my_type);
	get_search(gender, thumbCount, false, gg.countryCode, gg.stateCode);
	if (jQuery('#location-gender')) {
		set_gender(gender);	
	} 
};

function initLogin() {
	jQuery('#loginForm').validate({
		rules: {
			Email: {
				required: true,
				email: true
			},
			Password: "required"
		},
		messages: {
			Email: "Please enter your email address",
			Password: "Please enter your password"
		}
	});
};

function initMessage() {
	if (jQuery('.message-status').length > 0) {
		setTimeout(function() {
			jQuery('.message-status').fadeOut('slow', function() {
				jQuery(this).remove();
			});
		}, 2000);	
	}
};

function initIframe() {
	if (window.location == window.parent.location) {
		window.location = "/";
	}
};

function dialogBox(titleText, messageText, dialogButtons, dWidth, dHeight, upload, showClose, dialogClose, dialogButtonStyle, dialogTimeout) {
	jQuery('#dialog').dialog('destroy');
	if (upload !== null && upload == "upload") {
		dialogButtons['Close'] = function(){
			jQuery(this).dialog('close');
		};
	} else if (showClose !== null && showClose !== false) {
		if (typeof(showClose) == 'string') {
			var closeText = showClose;
		} else {
			var closeText = 'No';
		}
		dialogButtons[closeText] = function(){
			jQuery(this).dialog('close');
		};	
	}
	
	if (dWidth === null) {
		dWidth = 410;
	}
	
	if (dHeight === null) {
		dHeight = 120;
	}
				
	jQuery('#dialog').dialog({
		autoOpen: false,
		title: titleText,
		height: dHeight,
		minHeight:0,
		width: dWidth,
		modal: true,
		resizable: false,
		draggable: false,
		buttons: dialogButtons
	});
	
	jQuery('#dialog').dialog('open');
	
	if (dialogClose !== null && dialogClose === true) {
		var dc = jQuery('<a>').attr({'href':'#', 'class':'ui-dialog-close'});
		jQuery('#dialog').html('<p class="middle">'+messageText+'</p>').prepend(dc).click(function(event) {
			event.preventDefault();
			jQuery('#dialog').dialog('close');
		});
	} else {
		jQuery('#dialog').html('<p class="middle">'+messageText+'</p>');
	}
	
	if (dialogButtonStyle !== null && dialogButtonStyle !== false) {
		jQuery('.ui-dialog .ui-dialog-buttonpane button').addClass(dialogButtonStyle);
	}
	
	if (dialogTimeout !== null && dialogTimeout === true) {
		setTimeout(function(){
			jQuery('.ui-dialog').fadeOut('slow', function() {
				jQuery('#dialog').dialog('destroy');
			});
		}, 3000);
	}	
};
 
jQuery(document).ready(function() {
	storeTimezone();
	initMessage();
	
	jQuery("#searchForm").submit(function() {
		var errorMessage = "";
		var error = false;	
		/*
		if (jQuery('#AccountType:checked').val() === null) {
			errorMessage = "Please choose if you are a sugar daddy or baby.\n";
			error = true;
		}
		if (jQuery('#LookingForType:checked').val() === null) {
			errorMessage += "Please choose if you want to meet a sugar daddy or baby.\n";
			error = true;
		}
		*/
		
		if (jQuery('#StateCode').val() == "" && jQuery('#StateCode option:selected').text() == "Select") {
			errorMessage = "Please choose your search state.\n";
			error = true;
		}
		if(jQuery('#CountryCode').val() == "" && jQuery('#CountryCode option:selected').text() == "Select") {
			errorMessage = "Please choose your search country.\n";
			error = true;
		}
		
		if(error) {
			alert(errorMessage);
			return false;
		}
	});
});
