/*jQuery(window).load(function() {
	interfaceHandlerLoaderFunction();
});
*/

//if(!FlashDetect.installed)
//{
	jQuery(window).load(function() {
		interfaceHandlerLoaderFunction();
	});
//}

var interfaceHandlerLoaderFunction = function() {
	initInterfaceHandlerLoaderFunction();
	typeSelectorLoaderFunction();
	adHandlerLoaderFunction();
}

var initInterfaceHandlerLoaderFunction = function() {
		if(!(jQuery.browser.opera || jQuery.browser.msie)) {
//			jQuery("div.tba_wizard_placeholder").remove();
			jQuery("#tba_wizard_placeholder").remove();
			jQuery("div.tba_wizard").show();
		} else {
//			jQuery("div.tba_wizard_placeholder").hide();
			jQuery("#tba_wizard_placeholder").hide();
		}
		
		
		var wizard_container = jQuery('div.tba_wizard');
		var wizard_steps = jQuery('div.tba_wizard_step');
		var validation_url = "http://www.toboads.si/sl/wizard/validate".htmlDeentitize();
		var post_url = "http://www.toboads.si/sl/wizard/post".htmlDeentitize();
		var upload_url = "http://www.toboads.si/sl/wizard/imageUploadPopup".htmlDeentitize();
		var registered_url = "http://www.toboads.si/sl/home/registered".htmlDeentitize();

		var createHelpBox = function(id, message, container) {
			var help_container = jQuery('<div class="tba_help_container" for_element="' + id + '"><div class="content"></div><div class="ending"></div></div>').appendTo(container);
			help_container.hide();
			var content = help_container.children("div.content");
			content.html('<p>' + message + '</p>');
			var element = jQuery("#" + id);
			
			var pos = element.position();
			help_container.css("position", "absolute");
			help_container.css("left", pos.left - help_container.outerWidth() - 15 + "px");
			help_container.css("top", pos.top - 9 + "px");
			
			jQuery("div.tba_help_container[for_element=" + id + "]", wizard_container).attr("active", "false");
			help_container.attr("active", "true");
			
			positionHelpBox(id);
		}
		
		var positionHelpBox = function(for_element) {
			var help_box = jQuery("div.tba_help_container[for_element=" + for_element + "]", wizard_container);
			var element = jQuery("#" + for_element);
			var pos = element.position();
			help_box.css({
				position: "absolute",
				left: pos.left - help_box.outerWidth() - 15 + "px",
				top: pos.top - 9 + "px"
			});
		}
		
		var help_boxes = {
			title: "&lt;strong&gt;Naslov oglasa&lt;/strong&gt;&lt;br/&gt; je dolg do 25 znakov. Vsebuje lahko . , ? ! &#039; - : % &euro; $ / ali &amp;, a ločil in znakov ne ponavljajte. V besedi so lahko največ tri velike črke (npr. SLOvenija)".htmlDeentitize(),
			text_text: "&lt;strong&gt;Besedilo oglasa&lt;/strong&gt;&lt;br/&gt; je dolgo do 70 znakov. Vsebuje lahko . , ? ! &#039; - : % &euro; $ / ali &amp;, a ločil in znakov ne ponavljajte. V besedi so lahko največ tri velike črke (npr. SLOvenija)".htmlDeentitize(),
			text_shop: "&lt;strong&gt;Besedilo oglasa&lt;/strong&gt;&lt;br/&gt; je dolgo do 50 znakov. Vsebuje lahko . , ? ! &#039; - : % &euro; $ / ali &amp;, a ločil in znakov ne ponavljajte. V besedi so lahko največ tri velike črke (npr. SLOvenija)".htmlDeentitize(),
			link_text: "&lt;strong&gt;Ciljni naslov oglasa&lt;/strong&gt;&lt;br/&gt; je povezava (npr http://www.toboads.si), ki bo uporabnika ob kliku na oglas pripeljala do va&scaron;e spletne strani. Uporabite lahko do 1024 znakov. Povezava bo deloma vidna tudi v oglasu.".htmlDeentitize(),
			link_shop: "&lt;strong&gt;Ciljni naslov oglasa&lt;/strong&gt;&lt;br/&gt; je povezava (npr http://www.toboads.si), ki bo uporabnika ob kliku na oglas pripeljala do va&scaron;e spletne strani. Uporabite lahko do 1024 znakov. Povezava bo v oglasu ne bo vidna.".htmlDeentitize(),
			keywords: "V to polje vpi&scaron;ite ključne besede, vsako v svoji vrstici.&lt;br/&gt; Ključne besede so lahko posamezne besede ali kraj&scaron;e fraze.".htmlDeentitize(),
			email1: "Vpi&scaron;ite svoj polni email naslov.".htmlDeentitize(),
			email2: "Ponovno vpi&scaron;ite email iz zgornjega polja za potrditev.".htmlDeentitize(),
			passwd1: "Vpi&scaron;ite geslo, ki je dolgo &lt;strong&gt;najmanj 7 znakov&lt;/strong&gt;.&lt;br/&gt; Geslo je občutljivo na velike in male črke.".htmlDeentitize(),
			passwd2: "Ponovno vpi&scaron;ite svoje geslo za potrditev.".htmlDeentitize()
		};
		
		var step_1 = jQuery("div.tba_wizard_step:eq(0)");
		var step_2 = jQuery("div.tba_wizard_step:eq(1)");
		var step_3 = jQuery("div.tba_wizard_step:eq(2)");
		
		createHelpBox("title", help_boxes.title, step_1);
		createHelpBox("text", help_boxes.text_text, step_1);
		createHelpBox("text", help_boxes.text_shop, step_1);
		createHelpBox("link", help_boxes.link_text, step_1);
		createHelpBox("link", help_boxes.link_shop, step_1);
		createHelpBox("keywords", help_boxes.keywords, step_2);
		createHelpBox("email1", help_boxes.email1, step_3);
		createHelpBox("email2", help_boxes.email2, step_3);
		createHelpBox("passwd1", help_boxes.passwd1, step_3);
		createHelpBox("passwd2", help_boxes.passwd2, step_3);
	
		jQuery("div.tba_wizard_indicator a").css("cursor", "default");
		
		jQuery("div.tba_wizard_step:gt(0)").hide();
		
		/** EVENT HANDLERS **/
	
		/** FIRST STEP **/
		var step = wizard_steps.eq(0);
		step.find("div.tba_wizard_next_button>div:first").click(
			function() {
				jQuery(this).hide().next("div.indicator").show();
				clearErrors();
				jQuery("div.tba_wizard_step:visible input:not([edited=true])").val("");
				validateFirstStep();
			}
		).hover(
			function() {
				jQuery(this).children("img").attr("src", "/images/www/wizard/big_next_button_hover.png");
			},
			function() {
				jQuery(this).children("img").attr("src", "/images/www/wizard/big_next_button.png");
			}
		);
		step.find("div.tba_wizard_back_button").addClass("tba_disabled").unbind("click");
		
		// handle image upload popup
		jQuery("#image_upload").click(
			function() {
				window.open(
					upload_url,
					"image_upload_window",
					"status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=0,left=400,top=200,height=300,width=400"
				);
				return false;
			}
		);
		
		
		/** SECOND STEP **/
		var step = wizard_steps.eq(1);
		step.find("div.tba_wizard_next_button>div:first").click(
			function() {
				jQuery(this).hide().next("div.indicator").show();
				clearErrors();
				jQuery("div.tba_wizard_step:visible input:not([edited=true])").val("");
				validateSecondStep();
			}
		).hover(
			function() {
				jQuery(this).children("img").attr("src", "/images/www/wizard/next_button_hover.png");
			},
			function() {
				jQuery(this).children("img").attr("src", "/images/www/wizard/next_button.png");
			}
		);
		step.find("div.tba_wizard_back_button").click(
			function() {
				clearErrors();
				wizard_steps.hide().eq(0).show();
				positionHelpBox("title");
				positionHelpBox("text");
				positionHelpBox("link");
				activateTab(0);
			}
		).hover(
			function() {
				jQuery(this).children("img").attr("src", "/images/www/wizard/back_button_hover.png");
			},
			function() {
				jQuery(this).children("img").attr("src", "/images/www/wizard/back_button.png");
			}
		);
		
		
		/** THIRD STEP **/
		var step = wizard_steps.eq(2);
		step.find("div.tba_wizard_next_button>div:first").click(
			function() {
				jQuery(this).hide().next("div.indicator").show();
				clearErrors();
				jQuery(".tba_wizard_step:visible input:not([edited=true])").val("");
				validateThirdStep();
			}
		).hover(
			function() {
				jQuery(this).children("img").attr("src", "/images/www/wizard/next_button_hover.png");
			},
			function() {
				jQuery(this).children("img").attr("src", "/images/www/wizard/next_button.png");
			}
		);
		step.find("div.tba_wizard_back_button").click(
			function() {
				clearErrors();
				wizard_steps.hide().eq(1).show();
				positionHelpBox("keywords");
				activateTab(1);
			}
		).hover(
			function() {
				jQuery(this).children("img").attr("src", "/images/www/wizard/back_button_hover.png");
			},
			function() {
				jQuery(this).children("img").attr("src", "/images/www/wizard/back_button.png");
			}
		);
		
		
		
		/** RESIZE EVENT HANDLER **/
		
		jQuery(document).resize(
			function() {
				positionErrors();
			}
		);
		
		/** FIELD EVENT HANDLERS **/
		
		jQuery("input[type=text], textarea").focus(
			function() {
				var el = jQuery(this);
				if(!el.attr("edited")) {
					el.val("");
					el.attr("edited", "true");
				}
				jQuery("div.tba_error_container").fadeOut();
				if((new String(el.attr("class"))).match(/tba_invalid/))
					jQuery("div.tba_error_container[for_element=" + el.attr("id") + "]").fadeIn("fast");
				else {
					positionHelpBox(el.attr("id"));
					jQuery("div.tba_help_container[for_element=" + el.attr("id") + "][active=true]").fadeIn("fast");
				}
			}
		).blur(
			function() {
				jQuery("div.tba_error_container[for_element=" + jQuery(this).attr("id") + "]").fadeOut("fast");
				jQuery("div.tba_help_container[for_element=" + jQuery(this).attr("id") + "][active=true]").fadeOut("fast");
			}
		);
		
		jQuery("input[type=password]").focus(
			function() {
				var el = jQuery(this);
				if(!el.attr("edited")) {
					el.val("");
					el.attr("edited", "true");
				}
				jQuery("div.tba_error_container").fadeOut();
				if((new String(el.attr("class"))).match(/tba_invalid/))
					jQuery("div.tba_error_container[for_element=" + el.attr("id") + "]").fadeIn("fast");
				else
					jQuery("div.tba_help_container[for_element=" + el.attr("id") + "][active=true]").fadeIn("fast");
			}
		).blur(
			function() {
				jQuery("div.tba_error_container[for_element=" + jQuery(this).attr("id") + "]").fadeOut("fast");
				jQuery("div.tba_help_container[for_element=" + jQuery(this).attr("id") + "][active=true]").fadeOut("fast");
			}
		);
		
		jQuery("label").hover(
			function() {
				var for_id = jQuery(this).attr("for");
				jQuery("div.tba_error_container[for_element=" + for_id + "]").fadeIn("fast");
			},
			function() {
				var for_id = jQuery(this).attr("for");
				jQuery("div.tba_error_container[for_element=" + for_id + "]").fadeOut("fast");
			}
		);
		
		
		
		
		/** HELPER FUNCTIONS **/
		var clearErrors = function() {
			jQuery("div.tba_error_container").remove();
			jQuery("div.tba_wizard input").add("div.tba_wizard textarea").add("div.tba_wizard label").removeClass("tba_invalid");
		}
		
		var createErrorBox = function(id, messages) {
			jQuery("div.tba_wizard_step:visible").append('<div class="tba_error_container" for_element="' + id + '"></div>');
			var error_container = jQuery("div.tba_error_container:last").hide();
			var content = error_container.append('<div class="content"></div><div class="ending"></div>').find(".content");
			for(var i = 0; i < messages.length; i++) {
				content.append('<p>' + messages[i] + '</p>');
			}
			var element = jQuery("#" + id);
			error_container.css({
				position: "absolute",
				left: element.position().left - error_container.outerWidth() - 15,
				top: element.position().top - 9
			});
			element.addClass("tba_invalid");
			if(element.attr("type") == "checkbox")
				element.next("label").addClass("tba_invalid");
		}
		
		var positionErrors = function() {
			jQuery("div.tba_error_container", wizard_container).each(
				function() {
					var element = jQuery("#" + jQuery(this).attr("for_element"));
					jQuery(this).css({
						left: element.position().left - jQuery(this).outerWidth() - 15,
						top: element.position().top - 9
					});
				}
			);
		}
		
		
		var activateTab = function(index) {
			jQuery("li.tba_wizard_indicator a", wizard_container).removeClass("active").eq(index).addClass("active");
		}
		
		
		
		
		
		/** VALIDATORS **/
		
		var validateFirstStep = function() {
			// prepare post for validation
			var params = {
				ad_type: jQuery("#ad_type").val(),
				ad_title: jQuery("#title").val(),
				ad_description: jQuery("#text").val(),
				ad_url: jQuery("#link").val()
			};
			// make a JSON post
			jQuery.getJSON(validation_url, params, function(data) { handleFirstStep(data); });
		}
		
		var handleFirstStep = function(json) {
			jQuery(".tba_wizard_next_button:visible .indicator").hide().parent().find("div:first").show();
			if(json.validation.length == 0) {
				jQuery(".tba_wizard_step:visible").hide().next().show();
				positionHelpBox("keywords");
				activateTab(1);
			} else {
				// prepare errors
				if(typeof(json.validation.ad_title) !== 'undefined') {
					createErrorBox('title', json.validation.ad_title);
				}
				if(typeof(json.validation.ad_description) !== 'undefined') {
					createErrorBox('text', json.validation.ad_description);
				}
				if(typeof(json.validation.ad_url) !== 'undefined') {
					createErrorBox('link', json.validation.ad_url);
				}
				jQuery(".tba_error_container:first").fadeIn();
			}
		}
		
		var validateSecondStep = function() {
			// prepare post for validation
			var params = {
				ad_type: jQuery("#ad_type").val(),
				keywords: jQuery("#keywords").val()
			};
			// make JSON post
			jQuery.getJSON(validation_url, params, function(data) { handleSecondStep(data); });
		}
		
		var handleSecondStep = function(json) {
			jQuery(".tba_wizard_next_button:visible .indicator").hide().parent().find("div:first").show();
			if(json.validation.length == 0) {
				jQuery(".tba_wizard_step:visible").hide().next().show();
				positionHelpBox("email1");
				positionHelpBox("email2");
				positionHelpBox("passwd1");
				positionHelpBox("passwd2");
				activateTab(2);
			} else {
				// prepare error
				if(typeof(json.validation.keywords) !== 'undefined') {
					createErrorBox('keywords', json.validation.keywords);
				}
				jQuery(".tba_error_container").eq(0).fadeIn();
			}
		}
		
		var validateThirdStep = function() {
			// prepare post for validation
			var params = {
				email1: jQuery("#email1").val(),
				email2: jQuery("#email2").val(),
				passwd1: jQuery("#passwd1").val(),
				passwd2: jQuery("#passwd2").val(),
				tos_check: (jQuery("#tos_check").attr("checked"))? "yes": "no"
			}
			// make JSON post
			jQuery.getJSON(validation_url, params, function(data) { handleThirdStep(data); });
		}
		
		var handleThirdStep = function(json) {
			if(json.validation.length == 0) {
				// validated data, try post
				var params = {
					ad_type: jQuery("#ad_type").val(),
					ad_title: jQuery("#title").val(),
					ad_description: jQuery("#text").val(),
					ad_url: jQuery("#link").val(),
					keywords: jQuery("#keywords").val(),
					email1: jQuery("#email1").val(),
					email2: jQuery("#email2").val(),
					passwd1: jQuery("#passwd1").val(),
					passwd2: jQuery("#passwd2").val(),
					tos_check: (jQuery("#tos_check").attr("checked"))? "yes": "no"
				};
				// make final JSON post
				jQuery.getJSON(post_url, params, function(data) { handleFinalPost(data); });
			} else {
				jQuery(".tba_wizard_next_button:visible .indicator").hide().parent().find("div:first").show();
				// prepare errors
				if(typeof(json.validation.email1) !== 'undefined') {
					createErrorBox('email1', json.validation.email1);
				}
				if(typeof(json.validation.email2) !== 'undefined') {
					createErrorBox('email2', json.validation.email2);
				}
				if(typeof(json.validation.passwd1) !== 'undefined') {
					createErrorBox('passwd1', json.validation.passwd1);
				}
				if(typeof(json.validation.passwd2) !== 'undefined') {
					createErrorBox('passwd2', json.validation.passwd2);
				}
				if(typeof(json.validation.tos_check) !== 'undefined') {
					createErrorBox('tos_check', json.validation.tos_check);
				}
			}
			jQuery(".tba_error_container:first").fadeIn();
		}
		
		var handleFinalPost = function(json) {
			if(json.commit = true) {
				var message = 'Registracija v sistem ToboAds je uspela. Na va&scaron; e-naslov boste v nekaj minutah prejeli navodila za pričetek uporabe ToboAds ogla&scaron;evalskega sistema.'.htmlDeentitize();
			} else {
				var message = 'Registracija v sistem ToboAds žal ni uspela. Prosimo, poskusite znova.'.htmlDeentitize();
			}
			jQuery(".tba_wizard").children().remove();
			window.location = registered_url;
			//jQuery(".tba_wizard").css("background", "transparent").append('<div class="result">' + message + '</div>');
		}
		
//		jQuery(".tba_wizard_placeholder").remove();
		jQuery("#tba_wizard_placeholder").remove();
		jQuery(".tba_wizard").show();

/*		
		// show help on title
		positionHelpBox('title');
		jQuery("div.tba_help_container[for_element=title][active=true]").fadeIn("fast");
*/
		
}
