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

/* document ready function */
$(document).ready(function(){
	
	/* initialize all listeners on elements that could be added via AJAX as well */
	initializeListeners();
	
	/* activate lightBox plugin */
	$("a[@rel*=lightbox]").lightBox({ txtImage: "Slika", txtOf: "od" });
	
	/* 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;
	}
	
	/* attach the character counters to some of the textares */
	if ($("#ad_name").size() > 0) $("#ad_name").charCounter(40, { container: "#ad_name_counter" });
	if ($("#ad_location").size() > 0) $("#ad_location").charCounter(70, { container: "#ad_location_counter" });
	if ($("#ad_title").size() > 0) $("#ad_title").charCounter(70, { container: "#ad_title_counter" });
	if ($("#ad_mail").size() > 0) $("#ad_mail").charCounter(50, { container: "#ad_mail_counter" });
	
	/* blink the display message */
	if ($("div#displayMessage").size() > 0) $("div#displayMessage").fadeOut().fadeIn();
	
	/* show the explanation div */
	$("a.explanationDivShow").click(function(event) {
		event.preventDefault();
		var explanation = $(this).attr("rel");		// get the appropriate explanation
		var explanationOutput = $("div#" + explanation + "Explanation").html();
		if (explanationOutput == "") explanationOutput = $("div#notAvailableExplanation").html();
		if ($("div.explanationDivWrapper").css("display") == "none") {
			$("div#explanationDivContent").html(explanationOutput);
			$("div.explanationDivWrapper").css("top", (mouseY - 150) + "px");
			$("div.explanationDivWrapper").fadeIn("slow");
		} else if ($("div#explanationDivContent").html() != explanationOutput && $("div.explanationDivWrapper").css("display") != "none") {
			$("div#explanationDivContent").slideUp();
			$("div#explanationDivContent").html(explanationOutput);
			$("div.explanationDivWrapper").animate({ top:(mouseY - 150) + "px" }, 500);
			$("div#explanationDivContent").slideDown();
		} else {
			$("div#explanationDivContent").html(explanationOutput);
			$("div.explanationDivWrapper").fadeOut("slow");
		}
	});
	
});

function showWarningDiv(errorOutput) {
	$("div#warningDivContent").html(errorOutput);
	$("div.warningDivWrapper").css("top", (mouseY - 150) + "px");
	$("div.warningDivWrapper").fadeIn("slow");
}

function showOptionsDiv(divTop, divContent, distance) {
	$("div#optionsDivTop").html(divTop);
	$("div#optionsDivContent").html(divContent);
	$("div.optionsDivWrapper").css("top", (mouseY - distance) + "px");
	$("div.optionsDivWrapper").fadeIn("slow");
	initializeListeners();
}

/* initialize all listeners - this function can be called even after insertion of HTML code via AJAX */
function initializeListeners() {
	
	/* handle various actions */
	$("a.linkItemAction").unbind("click").click(function(event) {
		event.preventDefault();
		var link_action = $(this).attr("id");
		var item_id = $(this).attr("name");
		if (link_action == "linkPrintItem") {
			window.print();
			return true;
		} else if (link_action == "linkReportItem") {
			var div_html_top = "Prijavi oglas";
		} else if (link_action == "linkShareItem") {
			var div_html_top = "Povej naprej";
		} else if (link_action == "linkSaveItem") {
			var div_html_top = "Shrani oglas";
		}
		showOptionsDiv(div_html_top, "Prosimo, počakajte ...", 200);
		$.post("action/ajax", 
			{ action: link_action, id: item_id}, 
			function(data) {		
				$("div#optionsDivContent").html(data);
				initializeListeners();
				if (link_action == "linkSaveItem") {
					var savedItemsCount = parseInt($("span#savedItemsCount").html()) + 1;
					if (substr_count(data, "nahaja") == 0) {
						$("span#savedItemsCount").html(savedItemsCount);
					}
					setTimeout("$(\"a.optionsDivClose\").click();", 2500);		
				}
			}
		);
	});
	
	/* report an item (the form HTML code is inserted via AJAX) */
	$("input#submitReportButton").unbind("click").click(function(event) {
		event.preventDefault();
		$("input#submitReportButton").attr("disabled", "true");
		$("span#submitReportWait").fadeIn("slow");
		if (!$("#submitReportText").val()) {
			var errorOutput = "Prosimo, če lahko z nekaj besedami pojasnite, zakaj se vam oglas zdi neprimeren. Najlepša hvala za pomoč!";
			$("a.optionsDivClose").click();
			showWarningDiv(errorOutput);
			setTimeout("$(\"a.warningDivClose\").click();", 3000);
			return false;		
		}
		$.post("action/ajax", 
			{ action: "linkReportItemSubmit", id: $("input#submitReportId").val(), text: $("#submitReportText").val() }, 
			function(data) {		
				$("div#optionsDivContent").html(data);
				setTimeout("$(\"a.optionsDivClose\").click();", 2500);
				initializeListeners();
			}
		);	
	});
	
	/* share an item with friends (the form HTML code is inserted via AJAX) */
	$("input#submitShareButton").unbind("click").click(function(event) {
		event.preventDefault();
		$("input#submitShareButton").attr("disabled", "true");
		$("span#submitShareWait").fadeIn("slow");
		
		var errorOutput = "";
		if (!$("input#submitShareName").val()) errorOutput += "- niste podali svojega imena<br />";
		if (!$("#submitShareText").val()) errorOutput += "- niste napisali sporočila za prijatelje<br />";
		if (!$("input#submitShareEmail1").val() && !$("input#submitShareEmail2").val() && !$("input#submitShareEmail3").val()) errorOutput += "- niste podali nobenega veljavnega e-poštnega naslova<br />";
		
		if (errorOutput) {
			errorOutput = "Žal niste izpolnili vseh obveznih polj. Pomanjkljivi so sledeči podatki:<br /><br />" + errorOutput;
			$("a.optionsDivClose").click();
			showWarningDiv(errorOutput);
			setTimeout("$(\"a.warningDivClose\").click();", 6000);
			return false;	
		}
		
		$.post("action/ajax", 
			{ action: "linkShareItemSubmit", 
				id: $("input#submitShareId").val(), 
				name: $("input#submitShareName").val(), 
				email1: $("input#submitShareEmail1").val(), 
				email2: $("input#submitShareEmail2").val(), 
				email3: $("input#submitShareEmail3").val(), 
				text: $("#submitShareText").val() }, 
			function(data) {		
				$("div#optionsDivContent").html(data);
				setTimeout("$(\"a.optionsDivClose\").click();", 2500);
				initializeListeners();
			}
		);	
	});
	
	/* handle various actions */
	$("a.linkSimilarItem").unbind("click").click(function(event) {
		event.preventDefault();
		var link_action = $(this).attr("id");
		var item_id = $(this).attr("name");
		$("div#similarItemContent").animate({ opacity: 0.3 }, 800);
		$("div#similarItemTop").html("<b>Prosimo, počakajte ...</b>");

		$.post("action/ajax", 
			{ action: link_action, id: item_id}, 
			function(data) {		
				$("div#similarItemContent").animate({ opacity: 1.0 }, 500);
				$("div#similarItem").html(data).fadeIn("slow");
				initializeListeners();
			}
		);
	});
	
	/* pre-fill the email field */
	$("input#ad_contact_mail").unbind("keyup").keyup(function(event) {
		$("input#ad_mail").val($("input#ad_contact_mail").val());
	});
	
	$("input#ad_contact_mail").unbind("blur").blur(function() {
		$("input#ad_mail").val($("input#ad_contact_mail").val());
	});
	
	/* display the full location from inserted post number */
	$("input#ad_location_post").unbind("keyup").keyup(function(event) {
		value = new String($("input#ad_location_post").val());
		if (value.length == 4) {
			$("span#ad_location_full").fadeOut("slow");
			$.post("action/ajax", 
				{ action: "update location", post_number: value }, 
				function(data) {
					$("span#ad_location_full").html(data).fadeIn("slow");
					setTimeout("$(\"div#addItemMapPreviewLoading\").slideUp(\"slow\");", 1400);
					setTimeout("$(\"div#adLocationPlaceholder\").slideUp(\"slow\");", 1500);
					setTimeout("$(\"div#addItemMapPreview\").slideDown(\"slow\");", 1500);
				}
			);
		}
	});
	
	/* if the field is already filled out, fetch the map */
	postNumberValue = new String($("input#ad_location_post").val());
	if (postNumberValue.length == 4 && $("span#ad_location_full").html() == "") {
		$("input#ad_location_post").keyup();
	}
	
	/* find subcategories for category number 1 */
	$("select#ad_category_one").unbind("change").change(function() {
		value = $("select#ad_category_one option:selected").val();
		if (value == 0) {
			$("div#ad_categories_two").slideUp("slow").html("");
			$("div#ad_categories_three").slideUp("slow").html("");
		} else {
			$("div#ad_categories_three").slideUp("slow").html("");
			
			/* activate the appropriate HTML input field inside the form */
			if (value == 100000) {
				$("select#ad_condition_quality").attr("name", "ad_condition_inactive");
				$("input#ad_condition_age").attr("name", "ad_condition");
				$("div#itemConditionAge").slideDown();
				$("div#itemConditionQuality").slideUp();
			} else {
				$("select#ad_condition_quality").attr("name", "ad_condition");
				$("input#ad_condition_age").attr("name", "ad_condition_inactive");
				$("div#itemConditionQuality").slideDown();
				$("div#itemConditionAge").slideUp();
			}
			
			$.post("action/ajax", 
				{ action: "load category two", parent_category: value }, 
				function(data) {
					if (data == "additional categories not found") {
						$("div#ad_categories_two").slideUp("slow").html("");	
					} else {
						$("div#ad_categories_two").html(data).slideDown("slow");
					}
					initializeListeners();
				}
			);	
		}
	});
	
	/* find subcategories for category number 2 */
	$("select#ad_category_two").unbind("change").change(function() {
		value = $("select#ad_category_two option:selected").val();
		if (value <= 0) {
			$("div#ad_categories_three").slideUp("slow").html("");
		} else {
			$.post("action/ajax", 
				{ action: "load category three", parent_category: value }, 
				function(data) {
					if (data == "additional categories not found") {
						$("div#ad_categories_three").slideUp("slow").html("");	
					} else {
						$("div#ad_categories_three").html(data).slideDown("slow");	
					}
					initializeListeners();
				}
			);	
		}
	});
	
	/* dynamically add fields for photo upload */
	$("input.ph_local").unbind("change").change(function() {
		fieldNum = parseInt($(this).attr("rel"));
		$("div#photo_" + (fieldNum + 1) + "_div").slideDown("slow");
	});
	
	$("input.ph_web").unbind("change").change(function() {
		fieldNum = parseInt($(this).attr("rel"));
		$("div#ph_web_" + (fieldNum + 1) + "_div").slideDown("slow");
	});
	
	/* change the photo upload mode - local disk vs. online photos */
	$("a#file_upload_mode").unbind("click").click(function(event) {
		event.preventDefault();
		if ($("div#photos_upload").css("display") == "none") {
			$("a#file_upload_mode").html("Če želite oglasu dodati fotografije, ki se že nahajajo na spletu, kliknite tukaj.");
			$("div#photos_web").slideUp("slow");
			$("div#photos_upload").slideDown("slow");
			$("input.ph_web").val("");
		} else {
			$("a#file_upload_mode").html("Če želite oglasu dodati fotografije z vašega računalnika, kliknite tukaj.");
			$("div#photos_upload").slideUp("slow");
			$("div#photos_web").slideDown("slow");
			$("input.ph_local").val("");
		}
	});
	
	/* make the appropriate changes to the "add item" form, based on item type */
	$("input[name=ad_type]").unbind("click").click(function(event) {
		value = parseInt($("input[name=ad_type]:checked").val());
		if (value <= 0) {
			/* MODE: donate */
			$("span#switchAgreements").slideDown("slow");
			$("div#switchStudent").slideDown("slow");
			$("div.switchLocationDonate").slideDown("slow");
			$("div#switchLocationNeed").slideUp("slow");
			$("div#switchItemCondition").slideDown("slow");
			$("span#switchThankYou").slideDown("slow");
		} else {
			/* MODE: need */
			$("span#switchAgreements").slideUp("slow");
			$("div#switchStudent").slideUp("slow");
			$("div#switchLocationNeed").slideDown("slow");
			$("div.switchLocationDonate").slideUp("slow");
			$("div#switchItemCondition").slideUp("slow");
			$("span#switchThankYou").slideUp("slow");
		}
	});
	
	/* make the appropriate changes to the "edit item" form, based on item type */
	$("select#ad_type").unbind("click").click(function(event) {
		value = parseInt($("select#ad_type option:selected").val());
		if (value <= 0) {
			/* MODE: donate */
			$("div#switchFlood").slideDown("slow");
			$("div#switchStudent").slideDown("slow");
			$("div.switchLocationDonate").slideDown("slow");
			$("div#switchLocationNeed").slideUp("slow");
		} else {
			/* MODE: need */
			$("div#switchFlood").slideUp("slow");
			$("div#switchStudent").slideUp("slow");
			$("div.switchLocationDonate").slideDown("slow");
			$("div#switchLocationNeed").slideUp("slow");
		}
	});
	
	/* hide the fields if user wants to reactivate / delete their ad */
	$("input[name=ad_command]").unbind("change").change(function() {
		if ($("input[name=ad_command]:checked").val() == "edit") {
			$("div#editItemField").slideDown("slow");
		} else {
			$("div#editItemField").slideUp("slow");
		}
	});
	
	/* make sure that all telephone numbers consist of nothing but numbers */
	$("input#ad_contact_tel").unbind("keyup").keyup(function(event) {
		var contact_tel = new String($("input#ad_contact_tel").val());
		var contact_tel_output = new String("");
		for (i = 0; i < contact_tel.length; i++) {
			if (contact_tel.charAt(i) >= 0 && contact_tel.charAt(i) <= 9) {
				contact_tel_output += contact_tel.charAt(i);
			} else {
				$("input#ad_contact_tel").animate({ opacity:0.2 }, 200).animate({ opacity:1.0 }, 200);
			}
		}
		$("input#ad_contact_tel").val(contact_tel_output);
	});
	
	/* validate the form to add a new item */
	$("#addForm").unbind("submit").submit(function(event) {	
		errorOutput = "";
		
		/* agreed to terms? */
		if ($("input#ad_agree_one:checked").val() === undefined) {
			errorOutput += "- niste izjavili, da se strinjate s pogoji<br />";
		}
		
		var adType = $("input[name=ad_type]:checked").val();
		if (adType == "") {
			errorOutput += "- niste izbrali tipa oglasa (podarim / potrebujem)<br />";
		}
		
		if ($("input#ad_name").val() == "") {
			errorOutput += "- niste vnesli svojega imena ali vzdevka<br />";
		}
		
		if (adType == 0 || adType == 1) {
			if ($("input#ad_contact_tel").val() == "" && substr_count($("input#ad_contact_mail").val(), "@") == 0) {
				errorOutput += "- niste podali svojih kontaktnih podatkov<br />";
			}
		}
		
		if (adType == 0) {
			if ($("input#ad_location_post").val() == "") {
				errorOutput += "- niste podali svoje poštne številke<br />";
			}
		}

		if ($("select#ad_category_one option:selected").val() == 0) {
			errorOutput += "- niste izbrali ustrezne rubrike<br />";		
		}
		
		if (parseInt($("select#ad_category_one option:selected").val()) != 110000 && (!$("select#ad_category_two option:selected").val() || $("select#ad_category_two option:selected").val() == 0)) {
			errorOutput += "- niste izbrali ustrezne podrubrike<br />";		
		}
		
		if ($("input#ad_title").val() == "") errorOutput += "- za svoj oglas niste podali naslova<br />";
		if ($("#ad_description").val() == "") errorOutput += "- za svoj oglas niste podali opisa<br />";
		if ($("input[name=ad_exchange]:checked").val() == "") errorOutput += "- niste izbrali načina prevzema<br />";
		
		if (errorOutput == "") {
			$("input#submit_button").fadeOut("fast");
			return true;
		} else {
			errorOutput = "Žal niste izpolnili vseh obveznih polj. Pomanjkljivi so sledeči podatki:<br /><br />" + errorOutput;
			showWarningDiv(errorOutput);
			return false;
		}
	});
	
	/* validate the form to edit an existing item */
	$("#editForm").unbind("submit").submit(function(event) {	
		if ($("input[name=ad_command]:checked").val() == "edit") {
			errorOutput = "";
			
			if ($("select#ad_type option:selected").val() == "") {
				errorOutput += "- niste izbrali tipa oglasa (podarim / potrebujem)<br />";
			}
			
			if ($("input#ad_name").val() == "") {
				errorOutput += "- niste vnesli svojega imena ali vzdevka<br />";
			}
			
			if ($("input#ad_contact").val() == "" && $("input#ad_contact_tel").val() == "" && substr_count($("input#ad_contact_mail").val(), "@") == 0) {
				errorOutput += "- niste podali svojih kontaktnih podatkov<br />";
			}
	
			if ($("select#ad_category_one option:selected").val() == 0) {
				errorOutput += "- niste izbrali ustrezne rubrike<br />";		
			}
			
			if (parseInt($("select#ad_category_one option:selected").val()) != 110000 && (!$("select#ad_category_two option:selected").val() || $("select#ad_category_two option:selected").val() == 0)) {
				errorOutput += "- niste izbrali ustrezne podrubrike<br />";		
			}
			
			if ($("input#ad_title").val() == "") errorOutput += "- za svoj oglas niste podali naslova<br />";
			if ($("#ad_description").val() == "") errorOutput += "- za svoj oglas niste podali opisa<br />";
			if ($("input[name=ad_exchange]:checked").val() == "") errorOutput += "- niste izbrali načina prevzema<br />";
			
			if (errorOutput == "") {
				$("input#submit_button").fadeOut("fast");
				return true;
			} else {
				errorOutput = "Žal niste izpolnili vseh obveznih polj. Pomanjkljivi so sledeči podatki:<br /><br />" + errorOutput;
				showWarningDiv(errorOutput);
				return false;
			}
		} else {
			return true;	
		}
	});
	
	/* validate the form to log in and edit an existing item */
	$("#loginEditForm").unbind("submit").submit(function(event) {	
		errorOutput = "";
		
		if ($("input#ad_number").val() == "") errorOutput += "- niste vnesli številke oglasa<br />";
		if ($("input#ad_pass").val() == "") errorOutput += "- niste vnesli gesla za urejanje<br />";
		
		if (errorOutput == "") {
			return true;
		} else {
			errorOutput = "Žal niste izpolnili vseh obveznih polj. Pomanjkljivi so sledeči podatki:<br /><br />" + errorOutput;
			showWarningDiv(errorOutput);
			return false;
		}
	});
	
	/* validate the form to retrieve a lost password */
	$("#lostPassForm").unbind("submit").submit(function(event) {	
		errorOutput = "";
		
		if ($("input#ad_number_lost_pass").val() == "") errorOutput += "- niste vnesli številke oglasa<br />";
		if (substr_count($("input#ad_mail").val(), "@") == 0) errorOutput += "- niste vnesli veljavnega e-poštnega naslova<br />";
		
		if (errorOutput == "") {
			return true;
		} else {
			errorOutput = "Žal niste izpolnili vseh obveznih polj. Pomanjkljivi so sledeči podatki:<br /><br />" + errorOutput;
			showWarningDiv(errorOutput);
			return false;
		}
	});
	
	/* validate the admin "add IP address" form */
	$("#addIPForm").unbind("submit").submit(function(event) {	
		errorOutput = "";
		
		if (substr_count($("input#ip").val(), ".") != 3) errorOutput += "- niste podali veljavnega IP naslova<br />";
		
		if (errorOutput == "") {
			return true;
		} else {
			errorOutput = "Žal niste izpolnili vseh obveznih polj. Pomanjkljivi so sledeči podatki:<br /><br />" + errorOutput;
			showWarningDiv(errorOutput);
			return false;
		}
	});
	
	/* validate the admin "add suspicious word" form */
	$("#addWordForm").unbind("submit").submit(function(event) {	
		errorOutput = "";
		
		if ($("input#word").val() == "") errorOutput += "- niste podali sporne besede<br />";
		
		if (errorOutput == "") {
			return true;
		} else {
			errorOutput = "Žal niste izpolnili vseh obveznih polj. Pomanjkljivi so sledeči podatki:<br /><br />" + errorOutput;
			showWarningDiv(errorOutput);
			return false;
		}
	});
	
	/* validate the form to edit a partner */
	$("#editPartner").unbind("submit").submit(function(event) {
		errorOutput = "";
			
		if ($("input#ad_name").val() == "") {
			errorOutput += "- niste vnesli imena organizacije<br />";
		}
		
		if ($("input#ad_pass").val() == "") {
			errorOutput += "- niste vnesli željenega gesla za uporabo portala<br />";
		}
		
		if ($("input#ad_email").val() == "") {
			errorOutput += "- niste vnesli e-poštnega naslova<br />";
		}
		
		if ($("input#ad_location_post").val() == "") {
			errorOutput += "- niste vnesli poštne številke vaše organizacije<br />";
		}
		
		if ($("input#ad_contact").val() == "") {
			errorOutput += "- niste vnesli kontaktnih podatkov<br />";
		}
		
		if (errorOutput == "") {
			return true;
		} else {
			errorOutput = "Žal niste izpolnili vseh obveznih polj. Pomanjkljivi so sledeči podatki:<br /><br />" + errorOutput;
			showWarningDiv(errorOutput);
			return false;
		}
	});
	
	/* show and hide hidden divs */
	$("a.toggleHiddenDiv").unbind("click").click(function(event) {
		event.preventDefault();
		var field = $(this).attr("rel");		// get ID 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");
			}
		}
	});
	
	/* 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 options div */
	$("a.optionsDivClose").unbind("click").click(function(event) {
		event.preventDefault();
		$("div.optionsDivWrapper").fadeOut("slow");
	});
	
}

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;
}
