/**
 *
 * jq_keystone.js
 *
 * Copyright (c) 2007 Nose AG Design Intelligence
 *
 * $Date: 2007/05/10 14:56:12 $
 * $Rev: 1 $
 * $Author: NOSE
 *
 */

/**
 * add the following code in the header of your webpage
 *
 * <script type="text/javascript" src="[path to this file]/jq_keystone.js"></script>
 * <script language="JavaScript" type="text/javascript">
 *    $(document).ready(function(){
 *       Keystone.init();
 *       // add additional calls here
 *    });
 * </script>
 */

var Keystone = {
	/**
	* Global on ready initialisation.
	*/
	initReady : function(){
		// init body tags
		Keystone.initBodyTags();
		
		// init global functions
		Keystone.backLink();
		
		// white
		//Keystone.testWhite();
	},
	/**
	* Global on load initialisation.
	*/
	initLoad: function() {
		// add loaded flag
		jQuery("body").addClass("loaded");
	},
	/**
	* Initializes the body tags.
	*/
	initBodyTags: function() {
	
		// browser flag
		var bc = "";
		if (jQuery.browser.msie) {
			bc = "msie";
		}
		else if (jQuery.browser.mozilla) {
			bc = "mozilla";
		}
		 else if (jQuery.browser.safari){
			bc = "safari";
		}
		jQuery("body").addClass(bc);
	},
	/**
	* Adds the white css for testing.
	*/
	testWhite: function() {
		var c = document.createElement('link');
        c.type = 'text/css';
		c.rel = 'stylesheet';
 		c.title = 'white';
		c.href = 'style/white.css';
		jQuery('head')[0].appendChild(c);
	},
	/** 
	* Shows an overlay with a selection of search options.
	* @searchBarSelector Selector for the container.
	* @searchFormSelector Selector search form.
	* @searchInputSelector Selector search text input field.
	* @msgOptions Message "Optionen"
	* @optionSelectors Array with option selectors.
	* @msgScope Message Message "Suchbereich"
	* @scopeSelectors Array with scope selectors.
	*/
	searchOverlay : function(searchBarSelector,searchFormSelector,searchInputSelector, msgOptions, optionSelectors, msgScope, scopeSelectors) {
		
		// exclude ie6
		if (jQuery.browser.msie && jQuery.browser.version < 7) {
			return true;
		}
		
		// states
		var stateStayVisible = false;
		
		// references
		var elSearchBar = jQuery(searchBarSelector);
		var elSearchForm = jQuery(searchFormSelector);
		var elSearchInput = jQuery(searchInputSelector);
		var elSearchOptions = jQuery("#searchOptions");
		
		// init markup
		var markup = "<div id='searchOverlay' class='hide'><span class='label block'>"+msgOptions+"</span><fieldset id='overlayOptions' class='border'></fieldset><span class='label block paddingTop'>"+msgScope+"</span><fieldset id='overlayScope' class='border'></fieldset></div>";
		elSearchBar.append(markup);
		
		// reference to overlay
		var elSearchOverlay = jQuery("#searchOverlay");
		
		// init option fields
		for (var i = 0; i < optionSelectors.length; i++) {
			// field
			var optionSelector = optionSelectors[i];
			
			var elField = jQuery(optionSelector);
			var elLabel = elField.next();
			var elFieldId = elField.attr("id");
			var elFieldName = elField.attr("name");
			
			var elOverlayField = elField.clone();
			var elOverlayLabel = elLabel.clone();
			var elOverlayFieldId = "overlay_"+elFieldId;
			var elOverlayFieldName = "overlay_"+elFieldName;
			
			// prepare elements
			elOverlayField.attr("id",elOverlayFieldId);
			elOverlayField.attr("name",elOverlayFieldName);
			elOverlayLabel.attr("for",elOverlayFieldId);
			
			
			// events
			jQuery(elOverlayField).bind("click",function() { 
														  
				// get field
				var id = jQuery(this).attr("id");
				var fid = id.substring(8,id.length);
				
				// set value
				var c = jQuery(this).attr("checked");
				if (c == null) {
					c = false;	
				}
				jQuery("#"+fid).attr("checked",c);
				
				
				// state
				stateStayVisible = true;
				
				// bubble
				return true;
			});
			
	
			jQuery(elOverlayLabel).bind("click",function() {									 
				// state
				stateStayVisible = true;
				
				// bubble
				return true;
			});
			
			jQuery(elField).bind("click",function() {
				// get field
				var id = jQuery(this).attr("id");
				var oid = "overlay_"+id;
				
				// set value
				var c = jQuery(this).attr("checked");
				if (c == null) {
					c = false;	
				}
				jQuery("#"+oid).attr("checked",c);
				
				// bubble
				return true;
			});
			
			
			// append
			jQuery("#overlayOptions",elSearchOverlay).append(elOverlayField);
			jQuery("#overlayOptions",elSearchOverlay).append(elOverlayLabel);
			jQuery("#overlayOptions",elSearchOverlay).append("<br/>");
		}
		
		// scope fields
		for (var i = 0; i < scopeSelectors.length; i++) {
			// field
			var scopeSelector = scopeSelectors[i];
			
			var elField = jQuery(scopeSelector);
			var elFieldId = elField.attr("id");
			
			var elOverlayField = elField.clone();
			var elOverlayFieldId = "overlay_"+elFieldId;
			
			// prepare elements
			elOverlayField.attr("id",elOverlayFieldId);
			elOverlayField.show();
			
			// events
			jQuery(elOverlayField).bind("click",function() {
				
				// get field
				var id = jQuery(this).attr("id");
				var fid = id.substring(8,id.length);
				
				// set value
				var c = jQuery(this).attr("value");
				jQuery("#"+fid).attr("value",c);
				
				// state
				stateStayVisible = true;
				
				// bubble
				return true;
			});
	
			
			jQuery(elField).bind("click",function() {
				// get field
				var id = jQuery(this).attr("id");
				var oid = "overlay_"+id;
				
				// set value
				var c = jQuery(this).attr("value");
				jQuery("#"+oid).attr("value",c);
				
				
				// bubble
				return true;
			});
			
			
			// append
			jQuery("fieldset#overlayScope",elSearchOverlay).append(elOverlayField);
			jQuery("fieldset#overlayScope",elSearchOverlay).append("<br/>");
		}
	
		
		// events
		elSearchInput.bind("click",function(){
			// show
			if (elSearchOptions.css("display") != "block") {
				elSearchOverlay.show();
			}
			
			// don't bubble
			return false;									
		});
		jQuery("body").bind("click",function() {
			// hide
			if (! stateStayVisible) {
				elSearchOverlay.hide();
			}
			else {
				stateStayVisible = false;	
			}
			
			// bubble
			return true;
		});
		
	
		
	},
	/**
	* Shows data items based on the selector's value (e.g. value = abc -> shows elements with class='abc').
	* @selectSelector Select element selector.
	* @containerSelector Container of the elements to show/hide.
	*/
	dataSelector: function(selectSelector,containerSelector) {
		
		// references
		var elSelect = jQuery(selectSelector);
		var elContainer = jQuery(containerSelector);
		
		// init
		var dataItems = new Array();
		var elsOption = jQuery("option",elSelect);
		for (var i = 0; i < elsOption.length; i++) {
			var elOption = jQuery(elsOption[i]);
			var optionValue = elOption.attr("value");
			
			// items
			var items = jQuery("."+optionValue,elContainer);
			dataItems = dataItems.concat(items);
		}
		updateItems();
		
		// events
		elSelect.bind("change",updateItems);
		
		/*
		* Updates the items.
		*/
		function updateItems() {
			// value
			var value = jQuery(elSelect).attr("value");
			
			// update items
			for (var i = 0; i < dataItems.length; i++) {
				var ditem = jQuery(dataItems[i]);
				var dclass = jQuery(ditem).attr("class") + "";
				if (dclass.indexOf(value) >= 0) {
					ditem.removeClass("hide");	
				}
				else {
					ditem.addClass("hide");	
				}
			}	
		}
		
		
	},
	
	/** 
	* Royalty free calculator. 
	*/
	royaltyFreeCalculator: function(continueSelector) {
		
		// references
		var elRfcTotal = jQuery("#rfcTotal");
		var elContinue = jQuery(continueSelector);
		
		// prepare all royalty free images
		var rfcItems = jQuery(".rfc");
		var elsRfcSize = jQuery(".rfcSize");
		var elsRfcPrice = jQuery(".rfcPrice");
		jQuery(".rfc").each(function() {
			// rf image
			var elSelect = jQuery("select",this);
			
			// data selector
			Keystone.dataSelector(elSelect,this);
			
			// calculate
			elSelect.bind("change",updateCalculation);
		});
		updateCalculation();
			
		/*
		* Updates the calculation.
		*/
		function updateCalculation() {
			
			// items
			var total = 0;
			var valid = true;
			for (var i = 0; i < rfcItems.length; i++) {
				var rfcItem = rfcItems[i];
				
				// parse values
				var elSelect = jQuery("select",rfcItem);
				var selectVal = elSelect.attr("value");
				var rfcSize = jQuery("option:selected",elSelect).text();
				var rfcPrice = jQuery("."+selectVal,rfcItem).text();
				rfcPrice = parseFloat(rfcPrice.substring(0,rfcPrice.indexOf(" "))); // expects 123.00[space]CHF
				if (isNaN(rfcPrice)) {
					rfcPrice = "-";
					valid = false;
				}
				else {
					rfcPrice = rfcPrice.toFixed(2);	
				}
				
				// set values
				jQuery(elsRfcSize[i]).text(rfcSize);
				jQuery(elsRfcPrice[i]).text(""+rfcPrice);
				
				// total
				total += parseFloat(rfcPrice);
			}
			
			// total
			if (valid) {
				// total
				elRfcTotal.text(""+total.toFixed(2));
				
				// form
				elContinue.removeClass("disabled");
				elContinue.attr("disabled",false);
				
			}
			else {
				// total
				elRfcTotal.text("-");
				
				// form
				elContinue.addClass("disabled");
				elContinue.attr("disabled",true);
				
			}
	
		}
		
	},
	
	/** 
	* Disables a form submit.
	* @formSelector Selector form element.
	* @submitSelector Selector form submit to disable.
	* @fieldSelector Selector reference field.
	* @fieldValueDisable Value to disable the form.
	*/
	formDisabler: function(formSelector,submitSelector,fieldSelector,fieldValueDisable) {
		// references
		var elForm = jQuery(formSelector);
		var elField = jQuery(fieldSelector);
		var elSubmit = jQuery(submitSelector);
		
		// event
		elField.bind("change",checkForm);
		checkForm();
		
		/*
		* Checks the form.
		*/
		function checkForm() {
			// check value
			if (jQuery(elField).attr("value") != fieldValueDisable) {
				elSubmit.removeClass("disabled");
				elSubmit.attr("disabled",false);
			}
			else {
				elSubmit.addClass("disabled");
				elSubmit.attr("disabled",true);	
			}	
		}
	},
	
	/**
	* Reloads the opener.
	*/
	openerReload: function() {
		window.opener.reload();
	},
	
	/**
	* Modifies the location of the opener.
	* @loc The location.
	*/
	openerLocation: function(loc) {
		window.opener.location = loc;	
	},
	
	/**
	* Back links.
	*/
	backLink: function() {
		jQuery(".back").bind("click",function(){
			window.history.back();
			return false;
		});	
	},
	
	
	/* show/hide an element and changing the text of the clicked link */
	toggleText : function(linkId,expr,msgShowText,msgHideText,show,cookie,cookieOptions){
		// init
		if (show) {
			$(expr).removeClass("hide");
			showText(false,msgHideText);
		}
		else {
			$(expr).hide();
			hideText(false,msgShowText);			
		}
		
		// event
		$(linkId).click(function(){ 
			if (show) {
				hideText(true,msgShowText);								
			}
			else {
				showText(true,msgHideText);
			}
		});
		
		// shows the text
		function showText(slide,txtMsg) {
			$(linkId).html(txtMsg);
			$("#searchBar select").css({display:"inline"});	
			if (slide) {
				$(expr).slideDown(250); 
			}
			
			// state
			show = true;
			$.cookie(cookie,true,cookieOptions);
		}
		
		// hides the text
		function hideText(slide,txtMsg) {
		 	$(linkId).html(txtMsg);
			$("#searchOptions select").css({display:"none"});
			if (slide) {
		 		$(expr).slideUp(350); 
		 	}
			
			// state
			show = false;
			$.cookie(cookie,false,cookieOptions);
		}
	},
	/* show/hide an element and changing the class of the clicked link */
	toggleArrow : function(elId,expr,show){
		// init
		if (show) {
			$(expr).removeClass("hide");
			showArrow(false);
		}
		else {
			$(expr).hide();
			hideArrow(false);
		}
		// event
		$(elId).click(function(){ 
			if (show) {
				hideArrow(true);
			}
			else {
				showArrow(true);
			}
		});
		
		// shows the box
		function showArrow(slide) {
			$(elId).removeClass("collapsed");
			$(elId).addClass("expanded");
			if (slide) {
				$(expr).slideDown();
			}	
			// state
			show = true;		
			$.cookie('lightbox',true,{domain:'.keystone.ch'});
		}
		// hides the box
		function hideArrow(slide) {
			$(elId).removeClass("expanded");
			$(elId).addClass("collapsed");
			if (slide) {
			 	$(expr).slideUp();
			}
			// state
			show = false;
			$.cookie('lightbox',false,{domain:'.keystone.ch'});			
		}
	},
	 
	/* focus the given element */
	focusElement : function(elId){
		elId = "#" + elId;
		$(elId)[0].focus();
	},
	openPopup : function(path){
		popup = window.open(
			path, "Keystone", "status=no,resizable=no,menubar=no,toolbar=no,location=no,scrollbars=yes,dependent=yes,width=1014,height=714");
		popup.focus();
	},
	/* open a file in a popup */
	popupLink : function(selectorString, file){
		$(selectorString).click(function(){
			Keystone.openPopup(file);
			return false;
		});
	},
	/* hover effect for image object with caption and picture icons */
	picHover : function(el){
		$(el).hover(function(){
		  $(this).removeClass("pictureBox");
		  $(this).addClass("pictureBoxHover");
		},function(){
		  if ($(this).attr("class").indexOf("pictureBoxSelected") < 0){
		  	$(this).addClass("pictureBox");		  	
		  }	
		  $(this).removeClass("pictureBoxHover");	  		  
		});		
	},
	/* call a javascript confirmation prompt */
	confirmation : function(message){
		return confirm(message);	
	},
	/* show very first sibling element upon clicking, hide system message if present  */
	clickShow : function(linkExpr, wrapper, sysMsgExpr, ieselecthack){
		$(linkExpr).bind("click", function(){
			$(this).hide();
			$(wrapper).css("display", "inline");
			$(wrapper).css("z-index", "100");			
			$(sysMsgExpr).remove();
			if (ieselecthack) {
				Keystone.createWrapperIFrame(wrapper,"wrapperFrame");
			}
		});		
	},	
	apply : function(linkExpr, wrapper, elExpr, sysMsgId, sysMsg, goTo, ieselecthack){
		$(wrapper + " input[@type=button]" + ", " + wrapper + " input[@type=submit]").bind("click", function(){
			$(wrapper).hide();
			if (ieselecthack) {
				Keystone.deleteWrapperIFrame(wrapper);
			}
			var passValue = $(elExpr).val();
			$(linkExpr).show();
			$(linkExpr).after("<span id=\"" + sysMsgId + "\" class=\"sysMsg\">" + sysMsg + " '" + passValue + "' </span> ");
			if (typeof goTo != "undefined") {
    			window.location.href = goTo;
			}
		});		
	},
	/* hide options and show original link */
	cancel : function(linkExpr, wrapper, ieselecthack){
		$(linkExpr).bind("click", function(){
			$(wrapper).hide();
			if (ieselecthack) {
				Keystone.deleteWrapperIFrame(wrapper);
			}
			// show link
			var l1 = $(this).parent().parent().prev();
			var l2 = $(this).parent().prev();	
			// with form	
			if (l1.css("display") == "none") {
				l1.show();
			}
			// without
			if (l2.css("display") == "none") {
				l2.show();
			}	
		});
	},	
	/*  creates a wrapper iframe */
	createWrapperIFrame: function(wrapperId,c) {
		var w = $(wrapperId);		
		// params
		var fid = wrapperId.substring(1,wrapperId.length) + "_iframe";
		var ftop = w.css("top");
		var fleft = w.css("left");
		var fbottom = w.css("bottom");
		var fzindex = w.css("z-index") - 1;
		
		// iframe
		w.before("<iframe id='"+fid+"' class='"+c+"'  style='position:absolute;top:"+ftop+";bottom:"+fbottom+";left:"+fleft+"; z-index:"+fzindex+"' frameborder=0 scrolling=no marginwidth=0 src='' marginheight=1></iframe>");
	},
	/* deletes the wrapper iframe */
	deleteWrapperIFrame: function(wrapperId) {
		var fid = "#" + wrapperId.substring(1,wrapperId.length) + "_iframe";
		$(fid).remove(); 
	},	
	/* add highlight class to selected picture boxes */
	highlightSelection : function(selEl){
		$(selEl).click( function() {
			if(this.checked){
				$(this).parent().parent().parent().attr("class","pictureBoxSelected");
			} else{
				$(this).parent().parent().parent().attr("class","pictureBox");
			}
		});
	},
    /* slide toggler plugin */
    slideToggler: function(id, defaults) {
            // settings
            jQuery(id).slideToggler(defaults);
    },
    /* save slide toggler settings */
    saveSlideTogglerSettings: function(id) {
            // toggler params
            var classToggler = "h3.toggler";
            var classExpanded = "expanded";
            // event
            jQuery(id).click(function() {
                    // state
                    var togglers = jQuery(classToggler);
                    var ts = "";
                    for (var i = 0; i < togglers.length; i++) {
                            var c = jQuery(togglers[i]).attr("className");
                            if (c && c.match(classExpanded)) {
                                    ts = ts + i + ";";
                            }
                    }

                    // save settings
                $.cookie('viewfile',ts,{domain:'.keystone.ch'});
            });
    },
	/* select lightboxes */
	selectLightboxes: function(id) {
		$(id).click(function() {
			$("div.pictureBox").each(function(){
				// change class
				$(this).removeClass("pictureBox");
				$(this).addClass("pictureBoxSelected");
				// select checkbox
				$(this).find("input[@type='checkbox']").each(function(){
					$(this).attr("checked",true);
				});
			});
		});		
	},
	deselectLightboxes: function(id) {
		$(id).click(function() {
			$("div.pictureBoxSelected").each(function(){
				// change class
				$(this).removeClass("pictureBoxSelected");
				$(this).addClass("pictureBox");
				// select checkbox
				$(this).find("input[@type='checkbox']").each(function(){
					$(this).attr("checked",false);
				});
			});
		});	
	},
	/* search on main page */
	searchMain: function(id,lhref) {
		$(id).click(function() {
			// form parameters
			var options = $("#typology select");
			var param = "?" + options.serialize();
			// search
			window.opener.location.href = lhref + param;
			// focus
			window.opener.focus();
		});		
	},
	/* add to light box on main site */
	addToLightboxMain: function(id,sysMsgId,sysMsg,passValue,param) {
		$(id).click(function() {
			// status message in popup
			$(this).after("<span id=\"" + sysMsgId + "\" class=\"sysMsgPopup\">" + sysMsg + " <strong>" + passValue + "<strong></span> ");
			$(this).remove();
			
			// update opener window
			window.opener.location.href = window.opener.location.href + param;
			window.focus();
		});		
	},
	/* go to the main site */
	gotoMain: function(id,gotoHref) {
		$(id).click(function() {			
			// update opener window
			window.opener.focus();
			window.opener.location.href = gotoHref;
	});		
	},	
	initAutoReload : function(){
		// Das Cookie wird getestet
		Keystone.testAutoReload ();
	},
	doAutoReload : function(){
		// Das ist der eigentliche Ladebefehl
		if (typeof Keystone.formToReload != 'undefined' &&
            Keystone.formToReload.length > 0 ) {
			eval('document.'+ Keystone.formToReload+'.submit()');
		} else {
			location.reload();
		}
	},
	testAutoReload : function(){
		if($.cookie("AutoReload") == 'true') {
			// Steht das Cookie auf 'true' wird der Autoreload eingeschaltet
			Keystone.AutoReloadON();
		} else {
			// In allen andern Faellen werden die entsprechenden Links gezeigt
			Keystone.AutoReloadOFF();
		}
	},
	AutoReloadON : function(){
		// Die entsprechenden Links gezeigt
		$("#resultReload").hide();
		$("#resultAutoReloadON").hide();
		$("#resultAutoReloadOFF").show();

		// Das Cookie wird mit einem Tag Verfallsdatum auf 'true' gesetzt
		$.cookie("AutoReload",true,{domain:".keystone.ch", expires: 1});
		// Der Autoreload wird auf 10 mal eine Sekunde gesetzt
		AutoReloadAktiv = window.setTimeout("Keystone.doAutoReload()", 1000*60);
	},
	AutoReloadOFF : function(){
		// Die entsprechenden Links gezeigt
		$("#resultReload").show();
		$("#resultAutoReloadON").show();
		$("#resultAutoReloadOFF").hide();

		// Der Timer wird ausgeschaltet
		if(typeof AutoReloadAktiv != 'undefined') {
			window.clearTimeout(AutoReloadAktiv);
		}
		// Das Cookie wird mit einem Tag Verfallsdatum auf 'false' gesetzt
		$.cookie("AutoReload",false,{domain:".keystone.ch", expires: 1});
	}
};

jQuery(document).ready(function(){
		Keystone.initReady();
});
jQuery(window).load(function(){
		Keystone.initLoad();
});