
var pageVisit = new Object();
pageVisit.id = 0;

$(function(){
	
	confirmInitializedVariables(new Array(
		"carrierId",
		"copy",
		"country_code",
		"domainname",
		"formated_username",
		"keyword",
		"params",
		"s",
		"template",
		"template_path",
		"username",
		"vertical"
	));
	
	registerPageVisit();
	
	registerCacheBackgroundImagesIfIE6();
	registerCloseHoverEvent();
	registerClickToFocus();
	
	$("div#Container").registerResizeToFitPage({
		stretch: "height"
	});
	
});

$.fn.centerDialogToElement = function(arguments) {
	arguments = $.extend({
		horizontal: "",
		vertical: "",
		relativeTo: "document",
		top: 0,
		right: 0,
		bottom: 0,
		left: 0
	}, arguments);
	
	if (!$(this).exists()) {
		return false;
	}
	
	if (arguments.horizontal.length > 0) {
		
		if (typeof(arguments.right) == "string") {
			arguments.right = arguments.right.replace(/px/g,"");
		}
		if (typeof(arguments.left) == "string") {
			arguments.left = arguments.left.replace(/px/g,"");
		}
		
		var elementWidth = arguments.horizontal.getTotalWidth({margin:false});
		var elementLeftOffset = (arguments.relativeTo.substr(0,1)=="p")?arguments.horizontal.position().left:arguments.horizontal.offset().left;
		
		var dialogWidth = $(this).getTotalWidth({margin:false});
		
		if (dialogWidth > 0) {
			var dialogOffset = elementLeftOffset + ((elementWidth - dialogWidth) / 2.0) + parseInt(arguments.left) - parseInt(arguments.right);
			$(this).css({
				position: "absolute",
				left: dialogOffset.toFixed(0) + "px"
			});
		}
		
	}
	
	if (arguments.vertical.length > 0) {

		if (typeof(arguments.top) == "string") {
			arguments.top = arguments.top.replace(/px/g,"");
		}
		if (typeof(arguments.bottom) == "string") {
			arguments.bottom = arguments.bottom.replace(/px/g,"");
		}
		
		var elementHeight = arguments.vertical.getTotalHeight({margin:false});
		var elementTopOffset = (arguments.relativeTo.substr(0,1)=="p")?arguments.vertical.position().top:arguments.vertical.offset().top;
		
		var dialogHeight = $(this).getTotalHeight({margin:false});
		
		if (dialogHeight > 0) {
			var dialogOffset = elementTopOffset + ((elementHeight - dialogHeight) / 2.0) + parseInt(arguments.top) - parseInt(arguments.bottom);
			$(this).css({
				position: "absolute",
				top: dialogOffset.toFixed(0) + "px"
			});
		}
		
	}
	
	return true;
	
}

$.fn.centerTo = function(arguments) {
	arguments = $.extend({
		horizontal: "",
		vertical: "",
		relativeTo: "document",
		top: 0,
		right: 0,
		bottom: 0,
		left: 0
	}, arguments);
	
	if (!$(this).exists() || (arguments.horizontal.length == 0 && arguments.vertical.length == 0)) {
		return false;
	}
	
	var dialog = $(this);
	dialog.centerDialogToElement(arguments);
	
	var resizeArgs = arguments;
	
	// Center on window resize
	$(window).bind("resize", function() {
		dialog.centerDialogToElement(resizeArgs);
	});
	
	return true;
	
}

// http://www.mail-archive.com/discuss@jquery.com/msg02537.html
//  author: Klaus Hartl

$.clientCoords = function() {
	
	var dimensions = {width: 0, height: 0};
	
	if (document.documentElement) {
		dimensions.width = document.documentElement.offsetWidth;
		dimensions.height = document.documentElement.offsetHeight;
	} 
	else if (window.innerWidth && window.innerHeight) {
		dimensions.width = window.innerWidth;
		dimensions.height = window.innerHeight;
	}
	return dimensions;
	
}

function confirmInitializedVariables(chkVars) {
	
	var varsOk = true;
	var badVars = new Array();
	
	// Fix error
	for (var i in chkVars) {
		var varName = chkVars[i];
		if (typeof (window[varName]) == "undefined" || window[varName] == null) {
			varsOk = false;
			badVars.push(varName);
			window[varName] = "";
			// eval("var "+varName+" = '';");
		}
	}
	
	if (isDev() && !varsOk && badVars.length > 0) {
		$.ajax({
			type: "POST",
			url: "/ajax/jserrorlog.php",
			data: {
				phoneNumber: username,
				error: "Missing JS vars: " + badVars.join(", ")
			},
			complete: function(XMLHttpRequest, textStatus){
				// alert("complete");
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
				// alert("error");
			},
			success: function(data, textStatus){
				// alert("success");
			}
		});
	}
	
	// Return varsOk in case we want to prevent registering of event handlers.
	return varsOk;
	
}

$.fn.draggable = function() {
	if (!$(this).exists()) {
		return false;
	}
	
	$(this).bind("drag", function(event) {
		$(this).css({   
			top:(event.offsetY-document.body.scrollTop),   
			left:(event.offsetX-document.body.scrollLeft)   
		})
	});
	
	return true;
	
}

$.fn.exists = function() {
	
	return ($(this).length > 0)?true:false;
	
}

// Choose your favorite pngfix plugin and use it here!

$.fn.fixPNGs = function() {
	if (!$(this).exists()) {
		return false;
	}
	
	// Supersleight plugin (the best so far)
	$(this).supersleight({shim: "/images/blank.gif"});
	
	// ifixpng plugin 
	//	(there are 2 versions but 2 breaks EVERYTHING, SO USE VERSION 1)
	// 	ifixpng will * not * work for repeating backgrounds or input backgrounds
	/* $(this).show().ifixpng(); */
	
	return true;
	
}

function getKeyCodeFromEvent(event){
	
	var code = "";
	
	if (!event) {
		event = window.event;
	}
	
	if (event.keyCode) {
		code = event.keyCode;
	}
	else if (event.which) {
		code = event.which;
	}
	
	return code;
	
}

function getPageVisitId() {
	
	return pageVisit.id;
	
}

$.fn.getTotalHeight = function() {
	arguments = $.extend({
		border: true,
		margin: true,
		padding: true
	}, arguments);
	
	if (!$(this).exists()) {
		return 0;
	}

	var totalHeight = ($(this).height()>0)?$(this).height():$(this).css("height").replace(/px/g,"");

	var borderHeight = parseInt($(this).css("borderTopWidth")) + parseInt($(this).css("borderBottomWidth"));
	var marginHeight = parseInt($(this).css("margin-top")) + parseInt($(this).css("margin-bottom"));
	var paddingHeight = parseInt($(this).css("padding-top")) + parseInt($(this).css("padding-bottom"));

	if (arguments.border && borderHeight > 0) {
		totalHeight += borderHeight;
	}
	if (arguments.margin && marginHeight > 0) {
		totalHeight += marginHeight;
	}
	if (arguments.padding && paddingHeight > 0) {
		totalHeight += paddingHeight;
	}
	
	return totalHeight;
	
}

$.fn.getTotalWidth = function(arguments) {
	arguments = $.extend({
		border: true,
		margin: true,
		padding: true
	}, arguments);
	
	if (!$(this).exists()) {
		return 0;
	}

	var totalWidth = ($(this).width()>0)?$(this).width():$(this).css("width").replace(/px/g,"");

	var borderWidth = parseInt($(this).css("borderLeftWidth")) + parseInt($(this).css("borderRightWidth"));
	var marginWidth = parseInt($(this).css("margin-left")) + parseInt($(this).css("margin-right"));
	var paddingWidth = parseInt($(this).css("padding-left")) + parseInt($(this).css("padding-right"));

	if (arguments.border && borderWidth > 0) {
		totalWidth += borderWidth;
	}
	if (arguments.margin && marginWidth > 0) {
		totalWidth += marginWidth;
	}
	if (arguments.padding && paddingWidth > 0) {
		totalWidth += paddingWidth;
	}
	
	return totalWidth;
	
}

function isDev() { return false; }

/* 
 * http://gregwolejko.com/ie-detection-in-javascript/
 *	Author: Greg Wolejko
 *
 *	"Method that I proposed is based only on the version of JavaScript implemented in particular browser 
 *	and that won’t change."
*/

function isIE() { return /*@cc_on!@*/false; }
function isIE6(){ return false /*@cc_on || @_jscript_version < 5.7 @*/; }
function isIE7(){ return false /*@cc_on || @_jscript_version >= 5.7 @*/; }


/* 
 * http://www.sean.co.uk/a/webdesign/javascriptdelay.shtm
 *  Author: Sean McManus
 *  Editors: Michael Andrews, Artur Kraft, André Pirard
*/

function pauseJS(millis) {
	
	var date = new Date();
	var curDate = null;
	do { curDate = new Date(); } 
	while(curDate-date < millis);
	
	return true;
	
} 

//http://www.mattfarina.com/2007/02/01/preloading_images_with_jquery
//	author: Matt Farina

$.preloadImages = function() {
	
	for (var i = 0; i < arguments.length; i++) {
		$("<img />").attr("src", arguments[i]);
	}
	
	return true;
	
}

/*
 * http://roshanbh.com.np/2008/09/get-random-number-range-two-numbers-javascript.html
 *  Author: Roshan Bhattarai
 * 
 * function to get random number up to m
 */

function randomXToY(minVal,maxVal,floatVal) {
	
  var randVal = minVal+(Math.random()*(maxVal-minVal));
  
  return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
  
}

function registerCacheBackgroundImagesIfIE6() {
	
	if (isIE6()) {
		try {
			document.execCommand("BackgroundImageCache", false, true);
		}
		catch(err) {
			
		}
	}
	
	return true;
	
}

/* 
 * http://www.nabble.com/Can-you-improve-my-Bring-to-Front-code--td16867104s27240.html
 *  Author: cherry.austin@gmail.com
 *  Editor: Josh Nathanson-3
 *  Editor: Tim Younger
 *  
 * Add a "ClickToFocus" class to any element(s) that you want to have this functionality.
*/

var zmax = 0;

function registerClickToFocus() {

	$(".ClickToFocus").click(function(){
		
		// Calculate max zindex (from topmost ClickToFocus element)
		$(".ClickToFocus").each(function(){
			var cur = $(this).css("zIndex");
			zmax = cur > zmax++ ? $(this).css("zIndex") : zmax;
		});
		
		$(this).css("zIndex", "" + zmax);
		zmax++;
		
		$(this).children().each(function(){
			$(this).css("zIndex", "" + zmax);
		});
	});
	
	return true;
	
}

function registerCloseHoverEvent() {

	$(".Close").attr("title","Close");
	
	$(".Close").hover(
		function() {
			$(this).find("div.Hover").css({display:"block"});
		},
		function() {
			$(this).find("div.Hover").css({display:"none"});
		}
	);
	
	return true;
	
}

function registerPageVisit() {
	if (!isDev()) {
		return false;
	}
	
	var page = "thankyou";
	
	if ($("form#form input[name='action']").val() == "username") {
		page = "username";
	}
	else if ($("form#form input[name='action']").val() == "pin") {
		page = "password";
	}
	
	$.ajax({
		type: "POST",
	   	url: "/ajax/pagevisit.php",
	   	data: {			
			keyword: keyword,
			page: page,
			session: s,
			sitename: domainname,
			template: template,
			username: username,
			vertical: vertical
		},
		dataType: "json",
		complete: function (XMLHttpRequest, textStatus) {
			// alert("complete");
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			// alert("error");
		},
	   	success: function (data, textStatus) {
	    	// alert("success");
			
			if (data.page_visit_id > 0) {
				pageVisit.id = data.page_visit_id;
			}
			
	   	}
	});
	
	return true;
	
}

$.fn.registerResizeToFitPage = function(arguments) {
	arguments = $.extend({
		stretch: ""
	}, arguments);
	
	if (!$(this).exists()) {
		return false;
	}
	
	var element = $(this);
	var resizeArgs = arguments
	
	if (element.exists()) {
		$(window).bind("resize", function(){
			element.resizeToFitPage(resizeArgs);
		});
		element.resizeToFitPage(resizeArgs);
	}
	
	return true;
	
}

$.fn.resizeToFitPage = function(arguments) {
	arguments = $.extend({
		stretch: ""
	}, arguments);

	if (!$(this).exists()) {
		return false;
	}
	
	var stretch = arguments.stretch.substr(0,1); 
		
	if (stretch == "h" || stretch == "b") {
		
		var ch = ($(this).attr("id")=="Container")?$(this).getTotalHeight():$("div#Container").getTotalHeight();
		var wh = $(window).height();
		
		$(this).height(ch);
		if (ch < wh) {
			$(this).height(wh);
		}
		
	}
	
	if (stretch == "w" || stretch == "b") {
		
		var cw = ($(this).attr("id")=="Container")?$(this).getTotalWidth():$("div#Container").getTotalWidth();
		var ww = $(window).width();
		
		$(this).width(ww);
		if (cw > ww) {
			$(this).width(cw);
		}
		
	}
	
	return true;
	
}

$.fn.startBackgroundColorAnimation = function(arguments) {
	arguments = $.extend({
		bgColor1: "#000",
		fontColor1: "#fff",
		timeout1: 1,
		bgColor2: "#000",
		fontColor2: "#fff",
		timeout2: 1
	}, arguments);
	
	if (!$(this).exists()) {
		return false;
	}
	
	var args = arguments;
	
	$(this).animate({
		backgroundColor: args.bgColor1,
		color: args.fontColor1
	}, args.timeout1 * 1000).animate({
		backgroundColor: args.bgColor2,
		color: args.fontColor2
	}, args.timeout2 * 1000, function(){
		$(this).startBackgroundColorAnimation(args);
	});
	
	return true;
	
}

$.fn.startBackgroundImageAnimation = function(arguments) {
	arguments = $.extend({
		opacity1: 1,
		timeout1: 0.2,
		opacity2: 0,
		timeout2: 0.2
	}, arguments);
	
	if (!$(this).exists()) {
		return false;
	}
	
	var args = arguments;
	
	$(this).animate({
		opacity: args.opacity1
	}, args.timeout1 * 1000).animate({
		opacity: args.opacity2
	}, args.timeout2 * 1000, function(){
		$(this).startBackgroundImageAnimation(args);
	});
	
	return true;
	
}

$.fn.stopBackgroundImageAnimation = function() {
	if (!$(this).exists()) {
		return false;
	}
	
	var clearQueue = true;
	var gotoEnd = true;
	
	$(this).stop(clearQueue, gotoEnd);
	$(this).css("opacity","0");
	
	return true;
	
}

function trim(string) {
	return string.replace(/^\s+|\s+$/g,"");
}
