/* absolute path to the "loading" image */
var loadingImageAbsolutePath = "http://www.spindistribute.com/images/ajax-loader.gif";

/* get mouse position */
var mouseX = 0;
var mouseY = 0;
$(document).mousemove(function(e) { 
	mouseX = e.pageX;
	mouseY = e.pageY;
});
/* END :: get mouse position */

/* are we dealing with Google Chrome? */
var isChrome = /chrome/.test(navigator.userAgent.toLowerCase());
/* are we dealing with IE 6 or less? */
var isIElte6 = ($.browser.msie && parseFloat($.browser.version.substr(0, 3)) <= 6.0);

/* document ready function */
$(document).ready(function(){
	
	/* call an AJAX script every 2 minutes to prevent the session timeout */
	setInterval("preventTimeout();", 1000 * 120);
	
	/* initialize all listeners on elements that could be added via AJAX as well */
	initializeListeners();
	
	/* activate resizable textarea plugin (for all browsers except Google Chrome which already provides this functionality) */
	if (!isChrome) {
		if ($("textarea.resizable").size() > 0) $("textarea.resizable:not(.processed)").TextAreaResizer();
	}
	
	/* activate jQuery UI Button plugin */
	$("button, input:submit").button();
	
	/* activate jQuery UI Tabs plugin */
	$("#jQueryUITabs").tabs();
	
	/* activate jQuery UI Progressbar plugin */
	$("#jQueryUIProgressBar").progressbar({ value: 0 });
	
	/* activate jQuery UI inline datepicker plugin */
	$("div#datePickerInline").datepicker({minDate: 0, maxDate: "+20Y", changeYear: true, altField: "#datePickerInput", altFormat: "mm/dd/yy", defaultDate: $("#datePickerInput").val()});
	$("input#admin_time_from").datepicker({minDate: "-5Y", maxDate: "+5Y", changeYear: true, dateFormat: "yy-mm-dd", defaultDate: $("#time_from").val()});
	$("input#admin_time_to").datepicker({minDate: "-5Y", maxDate: "+5Y", changeYear: true, dateFormat: "yy-mm-dd", defaultDate: $("#time_to").val()});
	if ($("div#ui-datepicker-div").size() > 0) $("div#ui-datepicker-div").css("display", "none"); /* remove the 10px-high white line below the whole page */
	
	/* enable "loading" functionality on a subset of HTML elements */
	$(".loadingOnClick").click(function(event) {
		var alreadyLoading = $(this).attr("alreadyLoading");
		if (!alreadyLoading) {
			$(this).attr("alreadyLoading", "true");
			var newElementId = $(this).attr("id") + $(this).attr("name") + $(this).attr("rel") + "LoadingElement";
			$(this).val("Please, wait ...").after("<span id='" + newElementId + "' style='display:none; margin-left:10px;'><img src='" + loadingImageAbsolutePath + "' align='absmiddle' /></span>");
			$("span#" + newElementId).fadeIn("fast");
		}
	});
	
	/* fix the flash elements for IE browsers */
	flashObjects = document.getElementsByTagName("object");
	for (var i = 0; i < flashObjects.length; i++) {
		flashObjects[i].outerHTML = flashObjects[i].outerHTML;
	}
	
	/* blink the error message if it is present */
	$("div.errorDiv").animate({ opacity: 0.17 }, 600, function() { $(this).animate({ opacity: 1.0 }, 800); });
	
	/* blink the success message if it is present */
	$("div.successDiv").animate({ opacity: 0.17 }, 600, function() { $(this).animate({ opacity: 1.0 }, 800); });
	
	/* show the SmileyTech logo in colors */
	$("img#logoSmileyTech").hover(function() {
		var currentSrc = new String($(this).attr("src"));
		$(this).attr("src", currentSrc.replace("grayscale", "color"));
	}, function() {
		var currentSrc = new String($(this).attr("src"));
		$(this).attr("src", currentSrc.replace("color", "grayscale"));
	});
	
	/* slide down the login form */
	if (location.href.indexOf("#/log-in") != -1) {
		$("div#topNavigationHolder a").removeClass("active");
		$("a#topNavLogIn").addClass("active");
		$("div#headerParent h3").animate({ opacity: 0.0 }, 250);
		$("div#headerWrapper").animate({ height: "470px" }, 250);
		if (isIElte6) {
			$("div#rightBox").slideUp("fast");	
		}
	}
	$("a#topNavLogIn").click(function(event) {
		event.preventDefault();
		window.location.hash = "#/log-in";
		$("div#topNavigationHolder a").removeClass("active");
		$("a#topNavLogIn").addClass("active");
		$("div#headerParent h3").animate({ opacity: 0.0 }, 250);
		$("div#headerWrapper").animate({ height: "470px" }, 250);
		if (isIElte6) {
			$("div#rightBox").slideUp("fast");	
		}
	});
	
	/* make active input fields seem lighter */
	$("div#logInHiddenLeft input").focus(function() {
		$(this).addClass("active");
	});
	
	$("div#logInHiddenLeft input").blur(function() {
		$(this).removeClass("active");
	});
	
	/* make active registration input fields seem lighter */
	$("input.quickRegInputText").focus(function() {
		$("input.quickreg_spam_protection").val(10);
		if ($(this).val() == "your email here ...") $(this).val("");
		$(this).addClass("quickRegInputTextActive");
	});
	
	$("input.quickRegInputText").blur(function() {
		if ($(this).val() == "") $(this).val("your email here ..."); 
		$(this).removeClass("quickRegInputTextActive");
	});
	
	/* set the hover effect on table rows in control panel archives */
	$("table.cpArchive tr").hover(function() {
		$(this).addClass("trHover");
	}, function() {
		$(this).removeClass("trHover");
	});
	
	/* set the hover effect on table rows in control panel payment options */
	$("table.paymentOptionsTable tr").hover(function() {
		$(this).addClass("trPaymentOptionsHover");
	}, function() {
		$(this).removeClass("trPaymentOptionsHover");
	});
	$("table.paymentOptionsTable td.priceTd").hover(function() {
		$(this).addClass("priceTdHover");
	}, function() {
		$(this).removeClass("priceTdHover");
	});
	
	/* validate the registration form */
	$("#registerForm").submit(function(event) {	
		errorOutput = "";
		if ($("input#reg_email").val().indexOf("@") == -1 || $("input#reg_email").val().indexOf(".") == -1) {
			errorOutput += "- Your email address seems to be incorrect.<br />";
		}
		if ($("input#reg_email").val() == "" || ($("input#reg_email").val() != $("input#reg_email_repeat").val())) {
			errorOutput += "- Make sure to type in the same email address twice.<br />";
		}
		if ($("input#reg_password").val() == "" || ($("input#reg_password").val() != $("input#reg_password_repeat").val())) {
			errorOutput += "- Make sure to type in the same password twice.<br />";
		}
		if ($("input#captcha_number").val() == 1 && $("input#captcha").val().toUpperCase() != "K2G4X") errorOutput += "- Retype the text from the picture.<br />";
			else if ($("input#captcha_number").val() == 2 && $("input#captcha").val().toUpperCase() != "H26LS") errorOutput += "- Retype the text from the picture.<br />";
			else if ($("input#captcha_number").val() == 3 && $("input#captcha").val().toUpperCase() != "A8F4R") errorOutput += "- Retype the text from the picture.<br />";
			else if ($("input#captcha_number").val() == 4 && $("input#captcha").val().toUpperCase() != "J5HMT") errorOutput += "- Retype the text from the picture.<br />";
			else if ($("input#captcha_number").val() == 5 && $("input#captcha").val().toUpperCase() != "P3D7E") errorOutput += "- Retype the text from the picture.<br />";
		if (errorOutput == "") {
			return true;
		} else {
			showWarningDialog(errorOutput);
			return false;
		}
	});
	
	/* validate the forgotten password form */
	$("#forgottenPassForm").submit(function(event) {
		if ($("input#forgotten_email").val().indexOf("@") == -1 || $("input#forgotten_email").val().indexOf(".") == -1) {
			showWarningDialog("This email address seems to be invalid.");
			return false;
		} else {
			return true;
		}
	});
	
	/* validate the slide-down forgotten password form */
	$("#forgottenPassFormSlide").submit(function(event) {
		if ($("input#forgotten_email_slide").val().indexOf("@") == -1 || $("input#forgotten_email_slide").val().indexOf(".") == -1) {
			showWarningDialog("This email address seems to be invalid.");
			return false;
		} else {
			return true;
		}
	});
	
	/* validate the form for changing user's password */
	$("#changePassForm").submit(function(event) {	
		errorOutput = "";
		if ($("input#password_old").val() == "") errorOutput += "- You need to specify your current password.<br />";
		if ($("input#password").val() == "" || ($("input#password").val() != $("input#password_repeat").val())) {
			errorOutput += "- Make sure to type in the same password twice.<br />";
		}
		if (errorOutput == "") {
			return true;
		} else {
			showWarningDialog(errorOutput);
			return false;
		}
	});
	
	/* validate the add / edit monitored website form */
	$("#addMonitoredWebsiteForm").submit(function(event) {	
		var errorOutput = "";
		if ($("input#website_url").val().indexOf("http://") != 0 && $("input#website_url").val().indexOf("https://") != 0) {
			errorOutput += "- Website URL should start with &quot;http://&quot; or &quot;https://&quot; prefix.<br />";
			$("input#website_url").val("http://" + $("input#website_url").val());
			errorOutput += "- We added &quot;http://&quot; to the beginning of the URL.<br />";
		}
		if (errorOutput == "") {
			/* prevent multiple submits */
			$(this).find("input[type='image'], input[type='submit']").click(function() {
				return false;
			});
			return true;
		} else {
			showWarningDialog(errorOutput);
			return false;
		}
	});
	
	/* validate the add / edit monitored website form */
	$("#addKeywordExplorerForm").submit(function(event) {	
		var errorOutput = "";
		if (!$("input#primary_keyword").val()) {
			errorOutput += "- You should tell us your &quot;Primary Keyword&quot;.<br />";
		}
		if (errorOutput == "") {
			/* prevent multiple submits */
			$(this).find("input[type='image'], input[type='submit']").click(function(){
				return false;
			});
			return true;
		} else {
			showWarningDialog(errorOutput);
			return false;
		}
	});
	
	/* add keywords when ordering SEO Assistant and Competition Analyzer reports */
	$("input#report_raw_keywords").keyup(function() {
		var keywords = new String($(this).val());
		var keywordsArray = keywords.split(",");
		var output = "";
		var counter = 0;
		for (i = 0; i < keywordsArray.length; i++) {
			keywordsArray[i].replace(/^\s+|\s+$/g, "");
			if (keywordsArray[i].length > 0) {
				counter++;
				output = output + counter + ") " + keywordsArray[i] + "<br />";
			}
		}
		if (output == "") {
			output = "no keywords selected so far";
		}
		$("div#report_all_keywords_div").html(output);
		$("div#report_all_keywords_div").attr("rel", counter);
	});

	
	/* validate the order SEO Assistant report form */
	$("#addSEOAssistantForm").submit(function(event) {	
		var errorOutput = "";
		if ($("input#website_url").val().indexOf("http://") != 0 && $("input#website_url").val().indexOf("https://") != 0) {
			errorOutput += "- Website URL should start with &quot;http://&quot; or &quot;https://&quot; prefix.<br />";
			$("input#website_url").val("http://" + $("input#website_url").val());
			errorOutput += "- We added &quot;http://&quot; to the beginning of the URL.<br />";
		}
		if ($("div#report_all_keywords_div").attr("rel") < 1) {
			errorOutput += "- You need to specify at least one of your primary keywords.<br />";
		}
		if ($("div#report_all_keywords_div").attr("rel") > 10) {
			errorOutput += "- You can only specify up to 10 primary keywords.<br />";
		}
		if (errorOutput == "") {
			/* prevent multiple submits */
			$(this).find("input[type='image'], input[type='submit']").click(function(){
				return false;
			});
			return true;
		} else {
			showWarningDialog(errorOutput);
			return false;
		}
	});
	
	/* validate the order Competition Analyzer report form */
	$("#addCompetitionAnalyzerForm").submit(function(event) {	
		var errorOutput = "";
		if ($("input#website_url").val().indexOf("http://") != 0 && $("input#website_url").val().indexOf("https://") != 0) {
			errorOutput += "- Website URL should start with &quot;http://&quot; or &quot;https://&quot; prefix.<br />";
			$("input#website_url").val("http://" + $("input#website_url").val());
			errorOutput += "- We added &quot;http://&quot; to the beginning of the URL.<br />";
		}
		if ($("div#report_all_keywords_div").attr("rel") < 1) {
			errorOutput += "- You need to specify at least one of your primary keywords.<br />";
		}
		if ($("div#report_all_keywords_div").attr("rel") > 10) {
			errorOutput += "- You can only specify up to 10 primary keywords.<br />";
		}
		if (errorOutput == "") {
			/* prevent multiple submits */
			$(this).find("input[type='image'], input[type='submit']").click(function(){
				return false;
			});
			return true;
		} else {
			showWarningDialog(errorOutput);
			return false;
		}
	});
	
	/* validate the add / edit tracked website form */
	$("#addTrackedWebsiteForm").submit(function(event) {	
		var errorOutput = "";
		if ($("input#website_url").val().indexOf("http://") != 0 && $("input#website_url").val().indexOf("https://") != 0) {
			errorOutput += "- Website URL should start with &quot;http://&quot; or &quot;https://&quot; prefix.<br />";
			$("input#website_url").val("http://" + $("input#website_url").val());
			errorOutput += "- We added &quot;http://&quot; to the beginning of the URL.<br />";
		}
		if (errorOutput == "") {
			/* prevent multiple submits */
			$(this).find("input[type='image'], input[type='submit']").click(function(){
				return false;
			});
			return true;
		} else {
			showWarningDialog(errorOutput);
			return false;
		}
	});
	
	/* display fields to add a new keyword to a tracked website */
	$("a#addKeywordLink").click(function(event) {
		event.preventDefault();
		$("a#addKeywordLink").slideUp("slow");
		$("div#addKeywordFields").slideDown("slow");
	});
	
	/* validate the add / edit tracked keyword form */
	$("#addTrackedKeywordForm").submit(function(event) {	
		var errorOutput = "";
		if ($("input#added_keyword").val() == "") {
			errorOutput += "- You need to specify a keyword or a keyword phrase.<br />";
		}
		if (errorOutput == "") {
			/* prevent multiple submits */
			$(this).find("input[type='image'], input[type='submit']").click(function(){
				return false;
			});
			return true;
		} else {
			showWarningDialog(errorOutput);
			return false;
		}
	});
	
	/* validate the add / edit monitored backlink form */
	$("#addMonitoredBacklinkForm").submit(function(event) {	
		var errorOutput = "";
		if ($("input#target_url").val().indexOf("http://") != 0 && $("input#target_url").val().indexOf("https://") != 0) {
			errorOutput += "- Target URL should start with &quot;http://&quot; or &quot;https://&quot; prefix.<br />";
			$("input#target_url").val("http://" + $("input#target_url").val());
			errorOutput += "- We added &quot;http://&quot; to the beginning of the Target URL.<br />";
		}
		if ($("input#source_url").val().indexOf("http://") != 0 && $("input#source_url").val().indexOf("https://") != 0) {
			errorOutput += "- Link URL should start with &quot;http://&quot; or &quot;https://&quot; prefix.<br />";
			$("input#source_url").val("http://" + $("input#source_url").val());
			errorOutput += "- We added &quot;http://&quot; to the beginning of the Link URL.<br />";
		}
		if ($("input#num_links").val() < 1 || $("input#num_links").val() > 100) {
			errorOutput += "- Please, tell us the number of links to your website on each page of your partner's website.<br />";
		}
		if (substr_count($("input#datePickerInput").val(), "/") != 2 || $("input#datePickerInput").val().length < 8) {
			errorOutput += "- Please, select a valid expiration date for your backlink.<br />";
		}
		if (errorOutput == "") {
			/* prevent multiple submits */
			$(this).find("input[type='image'], input[type='submit']").click(function(){
				return false;
			});
			return true;
		} else {
			showWarningDialog(errorOutput);
			return false;
		}
	});
	
	/* validate the form for contacting the administrator */
	$("#contactAdministratorForm").submit(function(event) {	
		errorOutput = "";
		if ($("#message_body").val() == "") errorOutput += "- Please, write your message for the administrator.<br />";
		if (errorOutput == "") {
			return true;
		} else {
			showWarningDialog(errorOutput);
			return false;
		}
	});
	
	/* AJAX logic for processing SEO Assistant and Competition Analyzer reports and gradually displaying report progress */
	if ($("input#report_check").size() > 0) {
		var report_id = $("input#report_id").val();
		var report_status = $("input#report_status").val();
		var report_type = $("input#report_type").val();
		
		// periodically check the status of this report and update HTML code of the website accordingly
		updateReportToLatestVersion(report_id, report_status, report_type);	// function updateReportToLatestVersion/3 is declared at the end of this file
		setInterval(function() {
			updateReportToLatestVersion(report_id, report_status, report_type);	// function updateReportToLatestVersion/3 is declared at the end of this file
		}, 5000);
		
		// fork the processing server-side script for reports that are 'waiting' (this should never be necessary)
		if (report_status == "waiting" && !isNaN(report_id)) {
			$.post("action/ajax-cp-reports-process", { id: report_id, status: report_status, type: report_type });
		}
	}
	
	/* AJAX logic for processing Keyword Explorer reports and gradually displaying report progress */
	if ($("input#keyword_explorer_report_check").size() > 0) {
		var report_id = $("input#keyword_explorer_report_id").val();
		var report_status = $("input#keyword_explorer_report_status").val();
		var report_human_readable = $("input#keyword_explorer_human_readable").is(":checked");
		
		// periodically check the status of this report and update HTML code of the website accordingly
		updateKeywordExplorerReportToLatestVersion(report_id, report_status, report_human_readable, 0);
		setInterval(function() {
			updateKeywordExplorerReportToLatestVersion(report_id, report_status, report_human_readable, 0);
		}, 5000);
		
		// fork the processing server-side script for reports that are 'waiting' (this should never be necessary)
		if (report_status == "waiting" && !isNaN(report_id)) {
			$.post("action/ajax-cp-keyword-reports-process", { id: report_id, status: report_status, type: report_type });
		}
	}
	
	/* show the explanation box if user cannot view and edit some of the items because their subscription expired */
	if ($("input#items_unavailable").size() > 0) {
		if ($("input#items_unavailable").val() > 0) {
			var items_unavailable = $("input#items_unavailable").val();
			var explanationOutput = "You are <b>unable to view and edit " + items_unavailable + " of your items</b> because your subscription to this service has expired.<br /><br />";
			explanationOutput += "To be able to use those items again, please subscribe to this service once again.<br /><br />";
			explanationOutput += "Thank you!";
			showExplanationDialog(explanationOutput);
		}
	}
	
});

function showWarningDialog(errorOutput) {
	var dialogHTML = "<div class=\"ui-state-error ui-corner-all\" style=\"padding:4px 7px 4px 7px; margin-bottom:7px;\">";
	dialogHTML += "<span class=\"ui-icon ui-icon-alert\" style=\"display:inline; float:left; margin-right:5px\"></span>";
	dialogHTML += "<b>Warning:</b> There is something wrong.";
	dialogHTML += "</div>";
	dialogHTML += errorOutput;
	$("#dialog-message").html(dialogHTML);
	$("#dialog-message").dialog({
		title: "Warning",
		modal: true,
		width: 450,
		position: ["center", 250],
		buttons: { Ok: function() { $(this).dialog("close"); } }
	});
}

function showOptionsDialog(divTop, divContent, distance) {
	var dialogHTML = divContent;
	$("#dialog-message").html(dialogHTML);
	$("#dialog-message").dialog({
		title: divTop,
		modal: true,
		width: 450,
		position: ["center", distance],
		buttons: { Ok: function() { $(this).dialog("close"); } }
	});
	initializeListeners();
}

function showExplanationDialog(explanationOutput) {
	var dialogHTML = "<div class=\"ui-state-highlight ui-corner-all\" style=\"padding:4px 7px 4px 7px; margin-bottom:9px;\">";
	dialogHTML += "<span class=\"ui-icon ui-icon-info\" style=\"display:inline; float:left; margin-right:5px\"></span>";
	dialogHTML += "<b>Info</b>";
	dialogHTML += "</div>";
	dialogHTML += explanationOutput;
	var dialogMessageWidth = 450 + ((explanationOutput.length - 750) * 0.6);
	if (dialogMessageWidth < 450) dialogMessageWidth = 450;
	if (dialogMessageWidth > 750) dialogMessageWidth = 750;
	$("#dialog-message").html(dialogHTML);
	$("#dialog-message").dialog({
		title: "Explanation",
		modal: true,
		width: dialogMessageWidth,
		position: ["center", 150],
		buttons: { Ok: function() { $(this).dialog("close"); } }
	});
}

/* initialize all listeners - this function can be called even after insertion of HTML code via AJAX */
function initializeListeners() {
	
	/* activate jQuery UI Button plugin */
	$("button, input:submit").button();
	
	/* show and hide hidden divs */
	$("a.toggleHiddenDiv").unbind("click").click(function(event) {
		event.preventDefault();
		var field = $(this).attr("rel");		// get rel of the appropriate DIV
		if (field == "") {
			if ($("div.hiddenDiv").css("display") == "none") {
				$("div.hiddenDiv").slideDown("slow");
			} else {
				$("div.hiddenDiv").slideUp("slow");
			}
		} else {
			if ($("div.hiddenDiv[rel='" + field + "']").css("display") == "none") {
				$("div.hiddenDiv[rel='" + field + "']").slideDown("slow");
			} else {
				$("div.hiddenDiv[rel='" + field + "']").slideUp("slow");
			}
		}
	});
	
	/* show the explanation div */
	$("a.explanationDivShow").unbind("click").click(function(event) {
		event.preventDefault();
		var explanation = $(this).attr("rel");		// get the appropriate explanation
		var explanationOutput = $("div#" + explanation + "Explanation").html();
		if (explanationOutput == "" || explanationOutput == null) explanationOutput = $("div#notAvailableExplanation").html();
		showExplanationDialog(explanationOutput);
	});
	
	/* display images in a jQuery UI dialog box */
	$("a.bigBulletsItemScreenshots").unbind("click").click(function(event) {
		event.preventDefault();
		var title = $(this).attr("title");
		var html = "<div align=\"center\"><img src=\"" + $(this).attr("href") + "\" alt=\"Loading Screenshots, Please Wait ...\" /></div>";
		$("#dialog-message").html(html);
		$("#dialog-message").dialog({
			title: title,
			modal: true,
			width: 820,
			position: ["center", 88]
		});
	});
	
	/* show the confirmation box when user wants to delete something */
	$("input#submit_delete").unbind("click").click(function(event) {
		var showConfirmationBox = $(this).attr("rel");
		if (showConfirmationBox != "no") {
			event.preventDefault();
			var handle = $(this);
			$("#dialog-message").html("Do you really want to delete this?");
			$("#dialog-message").dialog({
				title: "Do you really want to delete this?",
				modal: true,
				width: 450,
				position: ["center", 170],
				buttons: { 
					Cancel: function() { $(this).dialog("close"); }, 
					'Delete': function() { 
						$(handle).attr("rel", "no");
						$(this).dialog("close");
						$(handle).click();
					}
				}
			});
		} else {
			return true;
		}
	});
	
	
	/* human readable large numbers in Keyword Explorer reports */
	$("input#keyword_explorer_human_readable").unbind("click").click(function(event) {
		var report_id = $("input#keyword_explorer_report_id").val();
		var report_status = $("input#keyword_explorer_report_status").val();
		var report_human_readable = $("input#keyword_explorer_human_readable").is(":checked");
		$("#jQueryUIProgressBar").fadeIn("fast");
		updateKeywordExplorerReportToLatestVersion(report_id, report_status, report_human_readable, 1);
	});
	
	/* select the order criteria for Keyword Explorer reports */
	$("a.KEROrderLink").unbind("click").click(function(event) {
		event.preventDefault();
		var criterium = $(this).attr("rel");
		if (criterium != $("input#keyword_explorer_report_order").val()) {
			$("input#keyword_explorer_report_order").val(criterium);
			var report_id = $("input#keyword_explorer_report_id").val();
			var report_status = $("input#keyword_explorer_report_status").val();
			var report_human_readable = $("input#keyword_explorer_human_readable").is(":checked");
			$("#jQueryUIProgressBar").fadeIn("fast");
			updateKeywordExplorerReportToLatestVersion(report_id, report_status, report_human_readable, 1);
		}
	});
	
	/* send a message to any user from the list of users in the admin panel */
	$("a.sendMessage").unbind("click").click(function(event) {
		event.preventDefault();
		var user_id = $(this).attr("rel");
		$.post("action/ajax-admin-send-message", 
			{ uid: user_id }, 
			function(data) {		
				showOptionsDialog("Send a Message", data, 150);
			}
		);
	});
	
	/* hide the warning div */
	$("a.warningDivClose").unbind("click").click(function(event) {
		event.preventDefault();
		$("div.warningDivWrapper").fadeOut("slow");
	});
	
	/* hide the explanation div */
	$("a.explanationDivClose").unbind("click").click(function(event) {
		event.preventDefault();
		$("div.explanationDivWrapper").fadeOut("slow");
	});
	
	/* hide the additional options div */
	$("a.optionsDivClose").unbind("click").click(function(event) {
		event.preventDefault();
		$("div.optionsDivWrapper").fadeOut("slow");
	});
	
	/* show the contact & live support options in the Control Panel */
	$("a.supportContentLink").unbind("click").click(function(event) {
		event.preventDefault();
		$.post("action/ajax-cp-support", 
			{ action: "showAdditionalOptions" }, 
			function(data) {		
				showOptionsDialog("Contact and Live Support", data, 150);
			}
		);
	});
	
	/* connect to the Live Support Department */
	$("a.liveSupportLink").unbind("click").click(function(event) {
		event.preventDefault();
		$("div#liveSupportDiv").html("Connecting ...").slideDown("slow").css("border-right-width", "5px").animate({ borderRightWidth:"100px" }, 6000);
		$.post("action/ajax-cp-support", 
			{ action: "connect" }, 
			function(data) {		
				$("div#liveSupportDiv").css("border-right-width", "1px");
				$("div.ui-dialog").animate({ top:"14px" }, 2000);
				$("div#liveSupportDiv").html(data);
				initializeListeners();
			}
		);
	});

}

function substr_count(haystack, needle, offset, length) {
    var pos = 0;
	var cnt = 0;
    haystack += "";
    needle += "";
    if (isNaN(offset)) offset = 0;
    if (isNaN(length)) length = 0;
    offset--;
 
    while ((offset = haystack.indexOf(needle, offset + 1)) != -1) {
        if (length > 0 && (offset + needle.length) > length) {
            return false;
        } else {
            cnt++;
        }
    }
 
    return cnt;
}

function getWindowSize() {
	var dimensions = new Array(2);
	var myWidth = 0, myHeight = 0;
	if (typeof(window.innerWidth) == "number") {
		/* non-IE */
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight )) {
		/* IE 6+ in "standards compliant mode" */
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if (document.body && (document.body.clientWidth || document.body.clientHeight )) {
		/* IE 4 compatible */
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	dimensions[0] = myWidth;
	dimensions[1] = myHeight;
	return dimensions;
}

function preventTimeout() {
	$.post("action/ajax-prevent-session-timeout", 
		{ prevent: "prevent" }, 
		function(data) {		
			timeout_prevented = true;
		}
	);	
}

function updateReportToLatestVersion(report_id, report_status, report_type) {
	var report_update = $("input#report_update").val();
	if (report_update == "true") {
		$.post("action/ajax-cp-reports-view", { id: report_id, status: report_status, type: report_type }, 
		function(data) {
			var response = $.parseJSON(data);
			if (response['status'] == "finished" || response['status'] == "error") {
				$("input#report_update").val("false");	// stop updating this report
			}
			
			if (response['status'] == "error") {
				var errorOutput = "Our software encountered an error while working on your report. Please, check this report again in 10-15 minutes.<br /><br />";
				errorOutput += "If this problem occurs several times in a row, please inform us about it! This way we can prevent errors like that.<br /><br />";
				errorOutput += "Thank you very much.";
				showWarningDialog(errorOutput);
			}
			
			for (i = 1; i <= 4; i++) {
				var tab_id = "tab" + i;
				var report_index = "report_" + i;
				$("div#" + tab_id).html(response[report_index]);
			}
			
			$("#jQueryUIProgressBar").progressbar("value", response['percentage']);
			
			if (response['percentage'] == 100) {
				setTimeout(function() { $("#jQueryUIProgressBar").fadeOut("slow"); }, 800);
			}
			
			$("div#exportKeywordExplorerReport").html(response['export']);
			
			if (response['status'] == "finished" && response['js']) {
				// execute the code that loads and displays Google charts
				eval(response['js']);
				$("div.hiddenChartWithJavascript").slideDown("slow");
			}
			
			initializeListeners();
		});
	}
}

function updateKeywordExplorerReportToLatestVersion(report_id, report_status, report_human_readable, force_update) {
	var report_order = $("input#keyword_explorer_report_order").val();
	var report_update = $("input#keyword_explorer_report_update").val();
	if (report_update == "true" || force_update == 1) {
		$.post("action/ajax-cp-keyword-reports-view", { id: report_id, status: report_status, human_readable: report_human_readable, order: report_order }, 
		function(data) {
			var response = $.parseJSON(data);
			if (response['status'] == "finished" || response['status'] == "error") {
				$("input#keyword_explorer_report_update").val("false");	// stop updating this report
			}
			
			if (response['status'] == "error") {
				var errorOutput = "Our software encountered an error while working on your Keyword Explorer report. Please, check this report again in 10-15 minutes.<br /><br />";
				errorOutput += "If this problem occurs several times in a row, please inform us about it! This way we can prevent errors like that.<br /><br />";
				errorOutput += "Thank you very much.";
				showWarningDialog(errorOutput);
			}
			
			var tableHeadingHTML = "<tr>" + $("table#keywordExplorerReport tr:first").html() + "</tr>\n";
			tableHeadingHTML = tableHeadingHTML + "<tr>" + $("table#keywordExplorerReport tr").eq(1).html() + "</tr>\n";
			$("table#keywordExplorerReport").html(tableHeadingHTML + response['content']);
			
			$("#jQueryUIProgressBar").progressbar("value", response['percentage']);
			
			if (response['percentage'] == 100) {
				setTimeout(function() { $("#jQueryUIProgressBar").fadeOut("slow"); }, 800);
			}
			
			$("div#exportKeywordExplorerReport").html(response['export']);
			
			initializeListeners();
		});
	}
}
