/// <reference path="jquery-vsdoc.js"/>
// Creating Global Namespace for Klubschule
// requires jQuery 1.3.2
var KLU = {
    debug: false,
    warnings: false,
	mustLoadMerkliste: true,
	smallWidth :480,
	smallHeight:510,
	largeWidth :800,
	largeHeight:800		
};
var Utils = {
    activateAJAXonIE6: true,
    browser: "",
    mapId: "GoogleMap",
    mapIdAjax: "GoogleMapAjax",
	strGACode: "UA-1730432-3",
	timer : null
};

KLU.initializeSite = function() {
    ///<summary>This method is called an page startup and initialize needed Javascripts</summary>
    $(document).ready(function() {
        if (KLU.debug === false && KLU.warnings === true && typeof console !== "undefined") {
            alert("Please deactivate Firebug for a better performance!");
        }

        if (typeof (_spbodyOnLoadWrapper) !== 'undefined') {
            _spbodyOnLoadWrapper();
        }

        if (Utils.browser == "IE6") {
            //DD_belatedPNG.fix('#mainNavi');
            //DD_belatedPNG.fix('#content');
            // for the print view we must hide the vml shapes of DD_relatedPNG plugin
            window.onbeforeprint = function() { $("shape").hide(); };
            window.onafterprint = function() { $("shape").show(); };
        }

        var searchLoc = $("#searchLocation");
        var searchTerm = $("#searchTerm");
        // create Dropdown
        if (searchLoc.length > 0) {
            searchLoc.selectbox();
        }
        //select event
        if (searchTerm.length > 0) {
            searchTerm.focus(function() { $(this).select(); });
        }

        KLU.TEASER.startSwitch(7);
		if(typeof doNotResizeIframe == "undefined" || doNotResizeIframe === false) {
			Utils.HELPER.setIframeHeight();
		}
        Utils.GOOGLEANALYTICS.add(Utils.strGACode);
        Utils.ANIMATION.slideSpecialOpening();

        //Used to cancel the enter event in the kursliste
        $("#WelcomeContent").live("keypress", function(e) {
            if (e.which == 13 && e.target.id != "kursSubmit") { //Pressed ENTER but in Submit button
                e.preventDefault();
                e.stopPropagation();
            }
        });
        //$('#tabpage1_gridLine_0').toggle().toggle();
    });

} ();


//{ #Region >>>>> SHAREPOINT FUNCTIONS

function ProcessDefaultOnLoad(onLoadFunctionNames){		
		//SharePoint ActiveX Fix
		ProcessPNGImages();
		UpdateAccessibilityUI();
		
		for (var i=0; i < onLoadFunctionNames.length; i++)
		{
			var expr="if(typeof("+onLoadFunctionNames[i]+")=='function'){"+onLoadFunctionNames[i]+"();}";
			eval(expr);
		}
		if (typeof(_spUseDefaultFocus)!=="undefined"){
			DefaultFocus();
		}
}

//} #Region <<<<< END - SHAREPOINT FUNCTIONS


//{ #Region >>>>> BROCHURE

KLU.getBrochure = function(url, formId, lang, title, errorMsg) {
    ///<summary>This function is specially for the ajax call of the brochure order site. 
    /// It collects the parameter and calls the given url and opens the brochure div.</summary>
    ///<param name="url" type="String" optional="false" mayBeNull="false">Url to post the request</param>
    ///<param name="formId" type="String" optional="false" mayBeNull="false">id of the from, which contains the form elements</param>
    var myBrochures = [];
    var subId = 'brochure_';
    var subIdLength = subId.length;

    $("#BrochureViewTable input:checked").each(function() {
        // ex of the id brochures_1728282728
        // we extract the guid and save it in the array 
        if (this.name.substring(0, subIdLength) == subId){
            myBrochures.push(this.name.substring(subIdLength));
		}
    });

    // compose the get url
    //url = "/_layouts/Migros.SP.MKS.Pages/BrochureBestellen.aspx";
    if (url.indexOf("?") == -1){
		url += "?";
	}
    url += "&jsEnabled=true&txtLang=" + lang + "&brochureitems=" + myBrochures.join(",");

    // show the thickbox
	title = title || "";
    if (myBrochures.length > 0){
        Utils.openFrameWindow(url, title);
    }else{
        alert(errorMsg);
	}
};

KLU.deleteBrochure = function(delClass) {
    ///<summary>Deletes a selected brochure.</summary>
    ///<param name="delClass" type="String" optional="false" mayBeNull="false">Class of the table row element</param>
    if ($("#PanelOrderForm .tblBroPost tr").length <= 1) {
        KLU.closeBrochureWindow();		
    }else {
        $("tr ." + delClass).fadeOut(400, function() {
            $(this).remove();
        });
	}
};

KLU.submitBrochure = function(formId) {
    ///<summary>Submits the form.</summary>
    ///<param name="formId" type="String" optional="false" mayBeNull="false">Id of the forms the should be submitted</param>
    if (WebForm_OnSubmit()) {
        var submitForm = $('#' + formId);
        var submitUrl = submitForm.attr("action");

        Utils.log("log", "Submitting Brochure Form To url: " + submitUrl);
        Utils.log("info", "with params:");
        Utils.log("dir", submitForm.serializeArray());

        $.post(submitUrl, submitForm.serializeArray(), function(data) {
            $("#TB_ajaxContent").empty().html(data);
        });
    }
};

KLU.bindBrochureEvents = function() {
    ///<summary>Bind the events for the order Form. Some Elements like the dropdowns have special events. These are binded by this function</summary>
    // Events for the dropdowns
    // if the upper dropdown is selected the center dropdown is changed
    // hsStandOrte is a variable that comes with the popup
    $("#ddlCenterStao").change(function() {
        var regionNr = $("option:selected", this).val();
        var arrRegions = hsStandOrte[regionNr];
        var ddlCenter = $("#ddlCenterName");
        Utils.log("info", "New Value selected: " + regionNr);

        ddlCenter.empty();
        for (var x in arrRegions) {
			if (arrRegions[x][0] !== ''){
				ddlCenter.append('<option value="' + arrRegions[x][1] + '">' + arrRegions[x][0] + '</option>');
			}
        }
        $("#ddlCenterName").parent().animate({ opacity: 0.5 }, 500);
        $("#ddlCenterName").parent().animate({ opacity: 1 }, 500);
    }).change();
};

KLU.closeBrochureWindow = function() {
    ///<summary>Closes the thickbox window</summary>    
    parent.tb_remove();
};

KLU.openBrochureWindow = function(url, windowTitle) {
    ///<summary>Opens the thickbox for brochure upload<summary>
    ///<param name="url" type="string" optional="false" mayBeNull="false">Url of the site which will be opened in the thickbox</param>
    ///<param name="windowTitle" type="string" optional="false" mayBeNull="true">Title of the thickbox window</param>
    windowTitle = windowTitle || "";
    Utils.openFrameWindow(url, windowTitle);
};

//} #Endegion <<<<< END - BROCHURE


//{ #Region >>>>> RECOMMEND SITE & EMAIL

KLU.openRecommendSite = function(url, windowTitle) {
    ///<summary>Opens the thickbox for "Seite weiterempfehlen" in course details<summary>
    ///<param name="url" type="string" optional="false" mayBeNull="false">Url of the site which will be opened in the thickbox</param>
    ///<param name="windowTitle" type="string" optional="false" mayBeNull="true">Title of the thickbox window</param>
    windowTitle = windowTitle || "";
    Utils.openFrameWindowSmall(url, windowTitle);
};

KLU.email = function(url, windowTitle) {
    ///<summary>Opens the thickbox for "Email senden" in course details<summary>
    ///<param name="url" type="string" optional="false" mayBeNull="false">Url of the site which will be opened in the thickbox</param>
    ///<param name="windowTitle" type="string" optional="false" mayBeNull="true">Title of the thickbox window</param>
    windowTitle = windowTitle || "";
    Utils.openFrameWindowSmall(url, windowTitle);
};

KLU.openPrintView = function(url, windowTitle) {
    ///<summary>Opens a new window for the print view<summary>
    ///<param name="url" type="string" optional="false" mayBeNull="false">Url of the site which will be opened in the window</param>
    ///<param name="windowTitle" type="string" optional="true" mayBeNull="true">Title of the window</param>	
    windowTitle = windowTitle || "";		
    window.open(url, "", "width="+KLU.largeWidth+",height="+KLU.largeHeight+",top=100,left=100,resizable=yes,scrollbars=yes,menubar=yes");
};

//} #Endregion <<<<< END - RECOMMEND SITE & EMAIL


//{ #Region >>>>> TEASER

KLU.TEASER = {

	startSwitch : function(seconds) {
		///<summary>Starts the switching of tehe teaser when site loads</summary>
		///<param name="seconds" type="Integer" optional="false" mayBeNull="false">The time in seconds the teaser switches</param>
		seconds = seconds || 7; // Standard is 7 seconds
		$(document).ready(function() {
			Utils.log("info", "Start teaser switch with "+seconds+" sec");
			var teaserRight = $('#contentSpartenTeaser .teaserRight');
			var teaserLeft = $('#contentSpartenTeaser .teaserLeft');
			var centerTeaser = $(".contentCenterTeaser");
			var duration = seconds * 1000;

			if ($('div', teaserRight).length > 1) {
				Utils.log('info', 'Found multiple Divs in Teaser Right, start switching');
				setInterval(function() { KLU.TEASER.switchTeaser(teaserRight); }, duration);
			}

			if ($('div', teaserLeft).length > 1) {
				Utils.log('info', 'Found multiple Divs in Teaser Left, start switching');
				setInterval(function() { KLU.TEASER.switchTeaser(teaserLeft); }, duration);
			}
			if(centerTeaser.length > 1) {
				centerTeaser.each(
					function(i) {
						if( $('div.rightTeaser', centerTeaser[i]).length > 1) {
							Utils.log('info', 'Found multiple Divs in centerTeaser, start switching');
							setInterval(function() { KLU.TEASER.switchTeaser(centerTeaser[i]); }, duration);
						}
					});
			}
			else {
				if ($('div.rightTeaser', centerTeaser).length > 1) {
					Utils.log('info', 'Found multiple Divs in centerTeaser, start switching');
					setInterval(function(){
						KLU.TEASER.switchTeaser(centerTeaser);
					}, duration);
				}
			}
		});
	}, // END StartSwitch
	
	switchTeaser : function(teaserDiv) {
		///<summary>This function is used for switching the teaser. It look in the given div if sub divs exist and switchs between them.</summary>
		///<param name="teaserDiv" type="jQuery Object" optional="false" mayBeNull="false">JQuery Object of parent div</param>
		var $active = $('DIV.active', teaserDiv);
		if ($active.length === 0) {
			var allDivs = $('DIV:first', teaserDiv).nextAll().hide();
			$active = allDivs.eq(allDivs.length - 1);
		}

		// use this to pull the divs in the order they appear in the markup
		var $next = $active.next().length > 0 ? $active.next() : $('DIV:first', teaserDiv);

		$active.hide();
		$next.show().css({ opacity: 0.0 }).addClass('active').animate({ opacity: 1.0 }, 1000, function() {
			$active.removeClass('active');
		});
	},
	
	showTeaserBox : function(title, url, size) {
		///<summary>Load the thickbox with the title and the given url. Also a parameter "ajax" ist send as get Request</summary>
		///<param name="title" type="String" optional="true" mayBeNull="false">The title of the thickbox window</param>
		///<param name="url" type="String" optional="false" mayBeNull="false">The url of the site which should be loaded</param>
		///<param name="size" type="Integer" optional="true" mayBeNull="false">Size of the Teaser 1 for large, 2 for small</param>    
		var diffToWindow = 200;
		var tbTitle = title || "Teaser Info";
			
		size = size || 1;
		var teaserWidth  = (size == 1) ?  KLU.largeWidth  : KLU.smallWidth;
		var teaserHeight = (size == 1) ?  KLU.largeHeight : KLU.smallHeight;

		if (typeof url === "undefined" || url === "") {
			Utils.log("error", "(KLU.getTeaserInfo) => url is empty.");
			return false;
		}

		var winHeight = $(window).height() - diffToWindow;
		if (winHeight > teaserHeight) {
			winHeight = teaserHeight;
		}

		if (url.indexOf("?") == -1) {
			url += "?";
		}
		url += "&height=" + winHeight + "&width="+teaserWidth+"&ajax";

		Utils.log("log", "(KLU.getTeaserInfo) => Loading: " + url);
		tb_show(tbTitle, url, null);    
		// manually track teaser PageView
		Utils.GOOGLEANALYTICS.trackTeaser(tbTitle, url);
	}

		
}; // END TEASER

function languageTest(niveau, langid) {
///<summary>This function is used by the authors to create a popup for the flash language tests</summary>
///<param name="niveau" type="String" optional="false" mayBeNull="false">Language Niveu eg A, B</param>
///<param name="langid" type="String" optional="false" mayBeNull="false">Language id</param>
    tb_remove();
	var popupWidth  = 670;
	var popupHeight = 660;
    var winWidth = $(window).width();
    var winHeight = $(window).height();
    var posLeft = parseInt((winWidth - popupWidth) / 2, 10);
    var posTop = parseInt((winHeight - popupHeight) / 2, 10);
    url = "/_layouts/Migros.SP.MKS.Pages/Teaser/Sprachtest.aspx?niveau=" + niveau + "&langid=" + langid;
    window.open(url, "", "width=" + popupWidth + ",height=" + popupHeight + ",top=" + posTop + ",left=" + posLeft + ",resizable=no,menubar=no");
	return false;
}

//} #Endregion <<<<< TEASER


//{ #Region >>>>> KURSLISTE

KLU.updateCourse = function(arrDivs) {
///<summary>This method is used when an ajax Request has modified the course list and you must restyle all checkboxes.</summary>
///<param name="arrDivs" type="Array" optional="false" mayBeNull="false">Array of Ids of the modified divs</param>

    if (!Utils.activateAJAXonIE6 && Utils.browser == 'IE6') {
        Utils.log("info", "KLU.updateCourse => activateAjaxOnIE6 is false.");
        return;
    }
       
    if (typeof arrDivs === 'undefined') {        
        arrDivs = ['body'];
    }

    Utils.log("info", "KLU.updateCourse => Activating checkboxes in : " + arrDivs.join(","));    
    
    for (var i = 0; i < arrDivs.length; i++) {
        // if method checkbox exists then call it				
        if (typeof $.ui !== "undefined") {
            $("input[type=checkbox]", $(arrDivs[i])).checkBox();
		}

        // adding style scrollbars and events for the checkboxes
        if ( arrDivs[i] == "#kursPanel" || arrDivs[i] == "#kursSelector" || arrDivs[i] == "body") {            
            $("#kursSelector span.ui-checkbox").click(function() {
                $(this).siblings("input").trigger("click");
            });
        }
    }
};

KLU.toggleGrantedHelpText = function() {
	if ( $(".bewilligungspflichtig", "#CourseTable").length > 0) {
		$("#GrantedHelpText").show();
	}else{
		$("#GrantedHelpText").hide();
	}
}

//} #Endregion <<<<< END - KURSLISTE


//{ #Region >>>>> HELPER
Utils.tb_CloseMessage = function(blnOnlyString) {
///<summary>This function overrides the close of the thickbox, because we have multilaguage content.</summary>
///<param name="blnOnlyString" type="Boolean" optional="true" mayBeNull="false">If true only the string is returned ond no dom element is manipulated.</param>

	blnOnlyString = blnOnlyString || false;
    strLang = Utils.Language || "de";
    var strMsg = "Schliessen";
    
    if (strLang == "fr") {        
		strMsg = "Fermer";
	}
	else if(strLang == "it") {
		strMsg = "Chiudere";
	}
		
	if (blnOnlyString){ return strMsg;}
	
	var objElm = $("#TB_closeAjaxWindow");
	var objLink = '<a href="#" onclick="tb_remove();" id="TB_closeWindowButton">' + strMsg + '</a>';
	objElm.html(objLink);
};

Utils.log = function(option, obj) {
    ///<summary>Logs data in the firebug console or creates a log window</summary>
    ///<param name="option" type="String" optional="false" mayBeNull="false">console methods (log, error, info, dir ....)</param>
    ///<param name="obj" type="Object" optional="false" mayBeNull="false">Any type of Javascrip Objects</param>
    if (!KLU.debug) {
		return;
	}

    if (typeof console !== "undefined") {
        console[option](obj);
    }
    else {
        if ($("#winConsole").length === 0) {
            $('body').append('<div id="winConsole"><h2>Loggin Window</h2></div>');
        }
        var text = '<p class="' + option + '">' + obj.toString() + '</p>';
        $("#winConsole").append(text);
    }
};

Utils.createGoogleMap = function() {
    Utils.log("info", "(Utils.createGoogleMap) => Start to create map");
    try {
        if (document.getElementById(Utils.mapIdAjax) !== null) {
            if ((typeof data !== "undefined") && (typeof data.MARKER !== "undefined")) {
                MAPS.createMap(Utils.mapIdAjax);
                for (var x in data.MARKER) {
                    if ((data.MARKER[x].lat !== "") && (data.MARKER[x].lng !== "")) {
                        MAPS.addSingleMarkerToMap(data.MARKER[x]);
                    }else{
                        MAPS.findLocation(data.MARKER[x]);
					}
                }
            }
            else {
                Utils.log("error", "(Utils.createGoogleMap) => No map data found!");
			}
        }
        else {
            Utils.log("info", "(Utils.createGoogleMap) => No google map div found");
		}
    }
    catch (err) {
        Utils.log("error", "(Utils.createGoogleMap => Exception in method: " + err);
    }
};

Utils.openFrameWindowSmall = function(url, title) {
    ///<summary>Opens the thickbox with a frame content <summary>
    ///<param name="url" type="string" optional="false" mayBeNull="false">Url of the site which will be opened in the thickbox</param>
    ///<param name="windowTitle" type="string" optional="false" mayBeNull="true">Title of the thickbox window</param>	
    Utils.openFrameWindow(url, title, KLU.smallWidth, KLU.smallHeight);
};

Utils.openFrameWindow = function(url, title, width, height) {
    ///<summary>Opens the thickbox with a frame content <summary>
    ///<param name="url" type="string" optional="false" mayBeNull="false">Url of the site which will be opened in the thickbox</param>
    ///<param name="windowTitle" type="string" optional="false" mayBeNull="true">Title of the thickbox window</param>
    ///<param name="width" type="integer" optional="true" mayBeNull="false">Width of the thickbox window</param>
    ///<param name="height" type="integer" optional="true" mayBeNull="false">Height of the thickbox window</param>
    var maxHeight = 500;
    var diffToWindow = 200; //50	
    width = width || KLU.largeWidth;
    height = height || $(window).height() - diffToWindow;

    if (height < maxHeight) {
		height = maxHeight;
	}

    tb_show(title, "blank.html?&height=" + height + "&width=" + width, null);    
    $("#TB_ajaxContent").append('<iframe border="0" frameborder="0" src="' + url + '" height="100%" width="100%"></iframe>');
};

//} #Region <<<<< END - HELPER

Utils.AJAX = {

	single : function(url, jDivId, data, typ, successFunc, blnLoad) {
	///<summary>Set up an ajax request to the given url. Used if only a div content changes. Faster than Utils.AJAX.multiple</summary>
	///<param name="url" type="String" optional="false" mayBeNull="false">url for the ajax request</param>
	///<param name="jDivId" type="string" optional="false" mayBeNull="false">id of div. Each id must begin with a #</param>
	///<param name="data" type="Object" optional="true" mayBeNull="true">Serialized Object for post request</param>
	///<param name="typ" type="string" optional="true" mayBeNull="false">POST or GET</param>
	///<param name="successFunc" type="Function" optional="true" mayBeNull="true">Function to be called after a successful ajax load</param>

		data = data || null;
		typ = typ || "GET";
		successFunc = successFunc || null;
		blnLoad = blnLoad || false;
		
		if (blnLoad){
			Utils.log("info", "Utils.AJAX.single  => Starting animation.");
			Utils.ANIMATION.startLoading([jDivId]);
		}

		Utils.log("info", "Utils.AJAX.single  => Starting ajax call to: " + url);
		$.ajax({
			dataType: "html",
			async: true,
			type: typ,
			data: data,
			url: url,
			timeout: 20000,
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				Utils.log("error", textStatus);
				Utils.ANIMATION.removeLoading([jDivId]);
			},
			success: function(data) {
				Utils.log("info", "Utils.AJAX.single => Ajax call successfull, updating " + jDivId);
				$(jDivId).replaceWith(data);
				KLU.updateCourse([jDivId]);
				
				if (successFunc !== null){
					successFunc();
				}
				
				if (blnLoad){			
					Utils.ANIMATION.removeLoading([jDivId]);
				}
			}
		});
	},//end load

	multiple : function(url, arrDivs, blnAnimate, blnLoading) {
		///<summary>Set up an ajax request to the given url. The second param contains an array of ids of the div, that will be changed. Notice that the ids in the request must be the same as in the html site.</summary>
		///<param name="url" type="String" optional="false" mayBeNull="false">url for the ajax request</param>
		///<param name="arrDivs" type="Array" optional="false" mayBeNull="false">An array of ids. Each id must begin with a #</param>
		///<param name="blnAnimate" type="Boolean" optional="true" mayBeNull="true">Set this value to true if you want that the new content is inserted with an smooth animation</param>
		///<param name="blnLoading" type="Boolean" optional="true" mayBeNull="true">If set to true a loading circle is shown while the ajax call</param>
		// set the default value
		blnAnimate = blnAnimate || false;
		blnLoading = blnLoading || false;

		
		
		if (blnLoading) {
			Utils.log("info", "Utils.AJAX.multiple  => Starting animation.");
			Utils.ANIMATION.startLoading(arrDivs);
		}

		// ajax call
		Utils.log("info", "Utils.AJAX.multiple  => Starting ajax call to: " + url);
		$.ajax({
			url: url,
			type: "GET",
			dataType: "html",
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				Utils.log("error", "Utils.AJAX.multiple  => "+ textStatus);
				if (blnLoading) {
					Utils.ANIMATION.removeLoading(arrDivs);
				}
			},
			success: function(xhrData) {
				Utils.log("info", "Utils.AJAX.multiple  => Ajax call sucess");
				var addScrollbar = false;
				var htmls = [];
				var obj = document.createElement("div");
				var ajaxObj = $(obj);
				ajaxObj.html(xhrData);
				var bCreateMap = $("#" + Utils.mapIdAjax, ajaxObj).length > 0;

				for (var i = 0; i < arrDivs.length; i++) {
					htmls[i] = $(arrDivs[i], ajaxObj).eq(0);
				}

				for (i = 0; i < arrDivs.length; i++) {
					if (arrDivs.length > 0) {
						Utils.log("log", "Try to Update: " + arrDivs[i]);
						try {
							$(arrDivs[i]).replaceWith(htmls[i]);
							Utils.log("info", "Utils.AJAX.multiple  => "+ arrDivs[i] + " successfully updated !!");
						}
						catch (err) {
							Utils.log("error", "Utils.AJAX.multiple  => Error: " + err.message);
						}

						//fade in
						if (blnAnimate) {
							$(arrDivs[i]).hide().fadeIn("slow");
						}
					}
					//Remove loading animation
					if (blnLoading) {
						Utils.ANIMATION.removeLoading(arrDivs);
					}
				}

				// updating checkboxes
				KLU.updateCourse(arrDivs);

				if (bCreateMap) {
					Utils.createGoogleMap();
				}

				//cleanup
				ajaxObj.remove();
				Utils.log("info", "End Method AjaxLoad");
			}
		});
	},
	
	lazyLoad : function(url) {
		///<summary>This method submits a form per ajax with all its parameters as a post request.</summary>
		var submitForm = $("form:first");
		var submitUrl = url;
		var serializeObj = submitForm.serializeArray();
		serializeObj.push({ name: "lazyloader", value: "1" });

		Utils.AJAX.single(submitUrl, "#kursPanel", serializeObj, "POST");
	}
	
};// END AJAX

Utils.ANIMATION = {

	startLoading : function(arrDivs){
		for (var i = 0; i < arrDivs.length; i++) {
			var currentDiv = $(arrDivs[i]);
			if ( $(".ajaxload", currentDiv).length <= 0 ) {
				$(currentDiv).append('<div class="ajaxload ajaxDiv"></div>');
				$(".ajaxload", currentDiv).height( currentDiv.height() );
			}
        }
	}, // startLoading
	
	removeLoading : function(arrDivs){
		for (var i = 0; i < arrDivs.length; i++) {			
			$(".ajaxload", arrDivs[i]).remove();
        }
	},

	slideSpecialOpening : function() {
		$(".specialOpenings").click(function() { $(this).find(".specialOpeningsContent").slideToggle("slow"); });
	}
}; // END ANIMATION

Utils.GOOGLEANALYTICS = {

	add : function(strCode) {
		///<summary>Adds the google analytics tracking code to each page<summary>
		///<param name="strCode" type="string" optional="false" mayBeNull="false">Google Tracking ID</param>
		if (typeof(_gat) === 'undefined') {
			gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
			gaJsUrl = gaJsHost + "google-analytics.com/ga.js";
			Utils.log("info", "Set tracking host, add ga.js to body. Tracking Code " + strCode);
			$.getScript(gaJsUrl, function(){
				Utils.log("info", "Script loaded: " + gaJsUrl);
				try {
					pageTracker = _gat._getTracker(strCode);
					pageTracker._trackPageview();
				} 
				catch (err) {
					Utils.log("error", "Tracking not initalized: " + err);
				}
			});
		}
		else {
			Utils.log("info", "Google Analytics Code already added");
		}	
	},
	
	getTeaserType : function (intType)  {
		var strType = "";
		switch(parseInt(intType, 10)) {
			case 0:
				strType = "Unknown";
				break;
			case 4:
				strType = "Centers";
				break;
			case 10:
				strType = "HomeLeft";
				break;
			case 11:
				strType = "HomeRight";
				break;
			case 2:
				strType = "Sparten";
				break;
			case 20:
				strType = "SpartenHinweis";
				break;
			case 30:
				strType = "MenuInfoText";
				break;
			case 31:
				strType = "MenuInfoCategory";
				break;
			case 32:
				strType = "MenuInfoTeaser";
				break;
			case 40:
				strType = "CrossBrand";
				break;
			default:
				strType = "Unknown";
				break; 
		}
		return strType;
	},
	
	trackTeaser : function(title, url) {
		///<summary>Tracks Teaser Click<summary>
		///<param name="title" type="string" optional="false" mayBeNull="false">Teaser Title</param>
		///<param name="url" type="string" optional="false" mayBeNull="false">Teaser URL</param>
		if(typeof(_gat) !== 'undefined') {
			var intType = Utils.GOOGLEANALYTICS.getUriParameter(url, "TeaserType");
			pageTracker._trackPageview("/teaser/" + Utils.GOOGLEANALYTICS.getTeaserType(intType) + "/" + title);
			Utils.log("info","/teaser/" + Utils.GOOGLEANALYTICS.getTeaserType(intType) + "/" + title);
		}
	},

	trackTeaser_1: function(intType, title) {
	        ///<summary>Tracks Teaser Click<summary>
        	///<param name="title" type="string" optional="false" mayBeNull="false">Teaser Title</param>
        	///<param name="url" type="string" optional="false" mayBeNull="false">Teaser URL</param>
        	if (typeof (_gat) !== 'undefined') {
            		pageTracker._trackPageview("/teaser/" + Utils.GOOGLEANALYTICS.getTeaserType(intType) + "/" + title);
            		Utils.log("info", "/teaser/" + Utils.GOOGLEANALYTICS.getTeaserType(intType) + "/" + title);
        	}
    	},

	getUriParameter : function(url, param) {
		var strSrc = url;
		var strParam = param; // Param Name
		strParam = strParam.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+strParam+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( strSrc );
		return ( results === null ) ? "" : results[1];
	},

	trackTabSwitch : function(obj) {
		///<summary>Tracks Tab Switching on Courselist<summary>
		///<param name="obj" type="string" optional="false" mayBeNull="false">Link Object</param>
		if(typeof(_gat) !== 'undefined') {
			var strHref = obj.attr("href");
			pageTracker._trackPageview(strHref);
			Utils.log("info","Tab switched: " + strHref);
		}
	}
};

Utils.COOKIES = {
	
	create : function (name, value, days, doescape) {
		var expires = "";
		if ((days) && (days > 0)) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			expires = "; expires=" + date.toGMTString();
		}    

		if (doescape===true){
			document.cookie = name + "=" + Utils.HELPER.encode(value) + expires + "; path=/";
		}
		else {
			document.cookie = name + "=" + value + expires + "; path=/";
		}
	},
	
	read : function(cookieName) {
		var theCookie = "" + document.cookie;
		var ind = theCookie.indexOf(cookieName);
		if (ind === -1 || cookieName === ""){
			return "";
		}
		var ind1 = theCookie.indexOf(';', ind);
		if (ind1 === -1){
			ind1 = theCookie.length;
		}
		return unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
	},

	resetMerklistenCookie : function (addMLCode, removeMLCode) { 
		var cv = Utils.COOKIES.read('MKS_MERKLISTE'); 
		var newval = '';
		var cvals = cv.split("&"); 
		var newpgdata = ''; 
		var alreadyPresent = false;
		
		for (var ival = 0; ival < cvals.length; ival++) { 
			var cdata = cvals[ival].split('='); 

			if (cdata.length == 2) { 
				if (cdata[0] != 'merkliste') { 
					if (newval.length > 0) { 
						newval = newval + '&'; 
					} 
					newval = newval + cvals[ival]; 
				} 
				else { //add merkliste 				
					var pgdata = cdata[1].split('|'); 
					for (pgidx = 0; pgidx < pgdata.length; pgidx++) { 
						if (pgdata[pgidx] != removeMLCode){ 
							
							if (newpgdata !== ''){ 
								newpgdata = newpgdata + '|'; 
							}else {
								newpgdata = 'merkliste=';
							}
								
							newpgdata = newpgdata + pgdata[pgidx]; 
						} 
						
						if (pgdata[pgidx] == addMLCode){ 
							alreadyPresent = true; 
						}
					} //for each 
				} //loop trough ml 
			} //cdata is valid 
		} //for all values in cookie 

		//add merkliste 
		if ((addMLCode !== '') && (alreadyPresent === false)) { 
			
			if (newpgdata !== '') {
				newpgdata = newpgdata + '|'; 
			}else {
				newpgdata = 'merkliste=';
			}
				
			newpgdata = newpgdata + addMLCode;    
		} 
		
		//add merklisten value 
		if (newpgdata !== '' ) { 
			if (newval.length > 0) {
				newval = newval + '&' ; 
			}
			newval = newval + newpgdata; 
		}	 

		Utils.COOKIES.create( 'MKS_MERKLISTE' , newval, 1, false ); 
	},
	
	resetPagingCookie : function(pageStartIndex, pageEndIndex, total, PgCurrent) {
		var cv = Utils.COOKIES.read('MKS_MERKLISTE');
		var newval = '';
		var cvals = cv.split("&");
		var newpgdata = '';

		for (ival = 0; ival < cvals.length; ival++) {
			var cdata = cvals[ival].split('=');

			if (cdata.length == 2) {
				if (cdata[0] != 'pageinfo') {
					if (newval.length > 0) {
						newval = newval + '&';
					}
					newval = newval + cvals[ival];
				}
				else { //add the paging info fo noncurrent pages
					var pgdata = cdata[1].split('|');
					for (pgidx = 0; pgidx < pgdata.length; pgidx++) {
						var pgdata1 = pgdata[pgidx].split('I');
						if (pgdata1[0] != PgCurrent) {
							if (newpgdata.length > 0) {
								newpgdata = newpgdata + '|';
							}else{
								newpgdata = 'pageinfo=';
							}
							newpgdata = newpgdata + pgdata[pgidx];
						}
					}
				}
			}
		}

		//add current paging info
		if (newpgdata.length > 0) {
			newpgdata = newpgdata + '|';
		}else{
			newpgdata = 'pageinfo=';
		}

		newpgdata = newpgdata + PgCurrent + 'I' + pageStartIndex + 'I' + pageEndIndex + 'I' + total;

		if (newval.length > 0) {
			newval = newval + '&';
		}

		newval = newval + newpgdata;
		//alert(newval)
		Utils.COOKIES.create('MKS_MERKLISTE', newval, 1, false); 
	}

};

Utils.HELPER = {
	
	expandAjaxUrl : function(url, controlIds) {
		return (url.indexOf('?') == -1)
			? url + '?ajax=true&controlid=' + controlIds
			: url + '&ajax=true&controlid=' + controlIds;
	},
	
	encode: function(string) {
        return escape(this._utf8_encode(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode: function(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }

        return utftext;
    },
	
	setIframeHeight : function() {
		///<summary>Changes dynamically the height of RegistrationFrame<summary>
			
		var frameId		= "RegistrationFrame";
		var objIframe 	= $("#"+frameId);		
		blnIsIframe 	= false;		
		
		//checken ob ich im iframe bin
		if (objIframe.length === 0 && typeof parent.frames[0]!== "undefined" ) {
			blnIsIframe = true;		
			objIframe = $("iframe", parent.document.body);
			if (objIframe.attr("id") != frameId) {
				blnIsIframe = false;
			}
		}
				
		// wenn nicht das richtige iframe dann raus hier
		if (!blnIsIframe){
			return;		
		}
								
		// Iframe höhe bestimmen
		var frameHeight = document.body.offsetHeight;
		if(typeof document.body.scrollHeight !== "undefined"){
			frameHeight = document.body.scrollHeight;
		}
				
		frameHeight += 20;									
		
		objIframe.height(frameHeight);
		objIframe.removeAttr("height");
		
		if ($.browser.safari || $.browser.opera ){				
			// Safari and Opera need a kick-start.
			var iSource = objIframe.src;
			objIframe.src = '';
			objIframe.src = iSource;					
		}						
	}

};

function RefreshNavigation(url, me, status) {
    ///<summary>Behaviour for the Navigation</summary>
    ///<param name="url" type="string" optional="false" mayBeNull="false">Url to be called</param>    
    ///<param name="status" type="integer" optional="true" mayBeNull="false">
    ///     1=Page reload, 2=Full Ajax + Teaser, 3=Ajax only navigation, 4=Ajax lazyload</param>
	if ( Utils.timer !== null ) {
		window.clearTimeout( Utils.timer );
	}
	
	// hide content an tab infos
	for (var i=1; i<=8; i=i<<1){
	    $("#tabpage" + i).hide();
	    if (i <= 2) {
	        $("#tab" + i).hide();
	        $("#_tab" + i).show();
	        $("#_taba1" + i).attr('href', url.replace("/kursliste.aspx", "/kurse/kursliste.aspx"));
	        $("#_taba2" + i).attr('href', url.replace("/kursliste.aspx", "/kurse/kursliste.aspx")+'&tabcode=2');
	        
	    }
		//if (i < 8) {
		//	$("#tab" +i+ " span").hide();
		//}
	}
	
	Utils.COOKIES.create('NavigationUrl', url, 0, true);
	
	status = status || 1;
	switch (status) {
	    case 2:
	        changeNavi(url, true);
	        break;
	    case 3:
	        changeNavi(url, false);
	        break;
	    case 4:
	        Utils.timer = window.setTimeout(function() { changeNavi(url, false, true); }, 700);
	        break;	        
	    default:
	        window.location.href = url;	       
	}		
	
	return false;
}

function changeNavi(url, blnLoadTeaser, blnLazyLoad) {
	///<summary>Set up the Ajax calls for the navigations</summary>
	///<param name="blnLoadTeaser" type="boolean" optional="true" mayBeNull="false">True if teaser schould be loaded</param>
	///<param name="status" type="integer" optional="true" mayBeNull="false">True for lazyload</param>    
	blnLoadTeaser = blnLoadTeaser || false;
	blnLazyLoad = blnLazyLoad || false;	
	
	if (blnLazyLoad) {
		Utils.log("info", "changeNavi => lazyload starting");
		Utils.AJAX.lazyLoad(Utils.HELPER.expandAjaxUrl(url, 'kursPanel'));
	} else {
		Utils.log("info", "changeNavi => Ajax call for Navi");
		var theurl = Utils.HELPER.expandAjaxUrl(url, 'kursPanel');
		var loadTeaserFunc = (blnLoadTeaser) 
			? function() {
				Utils.log("info", "changeNavi => Teaser refresh per ajax");
				var theurl = Utils.HELPER.expandAjaxUrl(url, 'contentSpartenTeaser');
				Utils.AJAX.single(theurl, "#contentSpartenTeaser", null, 'GET', KLU.startTeaserSwitching);}
			: null;	    
		Utils.AJAX.single(theurl, '#kursPanel', null, 'GET', loadTeaserFunc );
	}			
}

function RefershStaoContact(url) {
    var theurl = Utils.HELPER.expandAjaxUrl(url, 'StaoAndContakteContent');
    Utils.AJAX.multiple(theurl, ["#StaoAndContakteContent"], false);
    return false;
}

function RefreshGrid(url) {
	Utils.COOKIES.create('NavigationUrl', url, 0, true);

	if (url.toString().indexOf('tabcode=8', 0) == -1) {
	//if we are not on merkliste-tab, we have do enforce reload of merkliste after sort
	    KLU.mustLoadMerkliste = true;
	}

    var theurl = Utils.HELPER.expandAjaxUrl(url, 'kurse');
    //Utils.AJAX.multiple(theurl, ["#courseListing"], false, true);
	Utils.AJAX.multiple(theurl, ["#courseListing"], false, true);
    return false;
}

function ShowGrid(actPage, url) { 
///<summary>Switch between the tabs</summary> 
///<param name="url" type="string" optional="false" mayBeNull="false">ID of the tab opened</param> 
    
    Utils.COOKIES.create('NavigationUrl', url, 0, true); 

    if (actPage == 'tabpage8') { 
        loadMerkliste(url); 
    } 
   
    //Show page 
    $("div[id^='tabpage']").hide();   
    $("#"+actPage).show(); 
      
    //activate tab (bit shift because tab have ids tab1, tab2, tab4..) 
    for (var i=1; i<=8; i=i<<1) {   
     $("#tab"+i).removeClass("active"); 
	}
      
    var tabId = actPage.replace(/page/i, "");   
    $("#"+tabId).addClass("active"); 
  
	Utils.GOOGLEANALYTICS.trackTabSwitch($("#"+tabId+".active a")); 
      
    return false; 
}

function RefreshDetailTab(url) {
    var theurl = Utils.HELPER.expandAjaxUrl(url, 'KursDetails');
    Utils.AJAX.multiple(theurl, ["#KursDetails"]);
    return false;
}

function MerklisteAction(url, action) {
    var theurl = Utils.HELPER.expandAjaxUrl(url, "courseListing");
	Utils.AJAX.multiple(theurl, ["#courseListing"]);
    return false;
}

function MerklisteActionKD(url, action) {
    var theurl = Utils.HELPER.expandAjaxUrl(url, "KursDetails");
    Utils.AJAX.multiple(theurl, ["#KursDetails"]);
    return false;
}

function addMerklistItem(id, me, url) { 
    ///<summary>Adds an item to the merkliste per ajax</summary> 
    ///<param name="id" type="string" optional="false" mayBeNull="false">ID of the item</param> 
    ///<param name="me" type="Object" optional="false" mayBeNull="false">Reference to the clicked object</param> 
    ///<param name="url" type="string" optional="false" mayBeNull="false">Url to be called per ajax</param> 
    
    $(me).hide().siblings().fadeIn('slow'); //Show span 
    Utils.COOKIES.resetMerklistenCookie(id, ''); 
    $("span.anzahl").each(function(n) { 
        var tab = $(this).text(); 
        $(this).text(parseInt(tab, 10) + 1); 
		$("#tab8").removeClass("isEmpty");
    }); 
    KLU.mustLoadMerkliste = true; 
    return false; 
}

function deleteMerklistItem(id, me, url, PageSize) { 
///<summary>Removes an item from the merkliste per ajax</summary> 
///<param name="id" type="string" optional="false" mayBeNull="false">ID of the item</param> 
///<param name="me" type="Object" optional="false" mayBeNull="false">Reference to the clicked object</param> 
///<param name="url" type="string" optional="false" mayBeNull="false">Url to be called per ajax</param> 
    $(me).parents("tr:first").remove(); 
    Utils.COOKIES.resetMerklistenCookie('', id);
    var tab = 0;
    
    $("span.anzahl").each(function(n) { 
        tab = $(this).text(); 
		var newNbr = parseInt(tab, 10) - 1;
        $(this).text(newNbr);
		if (newNbr <= 0) {
			$("#tab8").addClass("isEmpty");
		}
    }); 
    
	if (tab == 1) { 
		$( "#tabpage8_PagingVon0" ).text( "0" ); 
		$( "#tabpage8_PagingVon1" ).text( "0" ); 
	} 

    var cid = "#cid" + id.toUpperCase(); 
    $(cid + " a").show().siblings().hide(); 
   
    return false; 
}

function loadMerkliste(url) { 
    if (KLU.mustLoadMerkliste === true) { 
        var theurl = Utils.HELPER.expandAjaxUrl(url, "courseListing"); 
        $("#tabpage8").append('<div id="AjaxOverlay" class="ajaxload"></div>'); 
        $.ajax({ 
            url: theurl, 
            type: "get", 
            dataType: "html", 
            async: true, 
            success: function(data) { 
                $("#tabpage8").html(data); 
                KLU.mustLoadMerkliste = false; 
            } 
        }); 
    } 
}

function MerklisteHandler() {
    try {
        //readyState of 4 or 'complete' represents  
        //that data has been returned  
        if (req.readyState == 4 ||
            req.readyState == 'complete') {
            alert(req.responseText);
        }
    }
    catch (e) {
        alert('Error in Ajax respose');
    }
}

//paging
function funcPagingNextButton(PageSize, PgCurrent) {
    var von = parseInt($("#" + PgCurrent + "_PagingVon0").text(), 10);
    var bis = parseInt($("#" + PgCurrent + "_PagingBis0").text(), 10);
    var total = parseInt($("#" + PgCurrent + "_PagingTotal").text(), 10);
    von = von + PageSize;
    bis = bis + PageSize;
    if (bis > total) {
        bis = total;
	}
    var i = Math.floor(von / PageSize) + 1;
    var btn = 'Pgbnt_' + parseInt(i, 10);
    funcPaging(btn, von-1, bis, PgCurrent);
}

function CallNavigationUrl(url) {
    ///<summary>Switch between the tabs</summary> 
    ///<param name="url" type="string" optional="false" mayBeNull="false">ID of the tab opened</param> 

    Utils.COOKIES.create('NavigationUrl', url, 0, true);
    window.location.href = url;	 
    
    return false;
}

function funcPaging(Pgbnt_current, pageStartIndex, pageEndIndex, PgCurrent) {

    var total = parseInt($("#" + PgCurrent + "_PagingTotal").text(), 10);
    Utils.COOKIES.resetPagingCookie(pageStartIndex, pageEndIndex, total, PgCurrent);
	KLU.toggleGrantedHelpText();

    $("#" + PgCurrent + "_PagingButtons0").find("li").removeClass();
    $("#" + PgCurrent + "_PagingButtons1").find("li").removeClass();
    $("#" + PgCurrent + "_" + Pgbnt_current + '0').addClass('selected');
    $("#" + PgCurrent + "_" + Pgbnt_current + '1').addClass('selected');

    $("#" + PgCurrent + "_PagingVon0").text(pageStartIndex + 1);
    $("#" + PgCurrent + "_PagingBis0").text(pageEndIndex);
    $("#" + PgCurrent + "_PagingVon1").text(pageStartIndex + 1);
    $("#" + PgCurrent + "_PagingBis1").text(pageEndIndex);

    $("#" + PgCurrent + "_kurstbody").find("tr").hide();
    for (var i = pageStartIndex; i < pageEndIndex; i++) {
        $("#" + PgCurrent + "_gridLine_" + i + "").show();
    }

    if (pageEndIndex >= total) {
        $("#" + PgCurrent + "_Pgbtn_next0").addClass('hidden');
        $("#" + PgCurrent + "_Pgbtn_next1").addClass('hidden');
    }
    else {
        $("#" + PgCurrent + "_Pgbtn_next0").removeClass().addClass('more');
        $("#" + PgCurrent + "_Pgbtn_next1").removeClass().addClass('more');
    }

    if (pageStartIndex == 1) {
        $("#" + PgCurrent + "_Pgbtn_prev0").addClass('hidden');
        $("#" + PgCurrent + "_Pgbtn_prev1").addClass('hidden');
    }
    else {
        $("#" + PgCurrent + "_Pgbtn_prev0").removeClass().addClass('less');
        $("#" + PgCurrent + "_Pgbtn_prev1").removeClass().addClass('less');
    }
    return false;
}