﻿/*
    Required: JQuery 1.2
    Author: Ueli Kunz
    lcid: 1031
*/

// returns get parameter value with name strParamName from current pages url (location.href)
function getURLParam(strParamName){
      var strReturn = "";
      var strHref = window.location.href;
      if ( strHref.indexOf("?") > -1 ){
        var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
        var aQueryString = strQueryString.split("&");
        for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
          if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
            var aParam = aQueryString[iParam].split("=");
            strReturn = aParam[1];
            break;
          }
        }
      }
      return unescape(strReturn);
} 

function emailHelper(){
	// gets all link elements that contains a mailto in their title attribute
	// the title contains further information. syntax is: title="mailto imtmedical marketing com"
	$("a[title~=mailto]").click(function sendMail(){
		var host = this.getAttribute("title").split(" ");
		window.open("mailto:"+host[2]+"@"+host[1]+"."+host[3]);
	});
}

function setSPResources(){
	
	initParams();
	
	/*
	* <input type="hidden" alt="txtPageLib" class="resource" runat="server" value="<%$Resources:custom,cfgPageLib%>" />
	* Dieses input-feld hat als value einen wert aus der resource-datei der aktuellen sprache. Der wird dann in das Feld mit der ID vom alt attribute geschrieben.
	* Dieser resourcen-text wird durch diese funktion in dem array langTemplates['<alt attribut wert>']['resText] zur verfügung gestellt.
	* im weiteren können in dem resourcen wert platzhalter definiert werden z.B. {keywords_entered} . Die Platzhalter werden auch in
	* dem langTemplates['alt attribute wert']['platzhalter'] definiert und dann wird jeder platzhalter in dem resource string durch den js-wert ersetzt.
	* langTemplates wird in initParams() in der masterpage deklariert.
	*/
	
	$("input[class='resource']").each(function(index){
		// target element that will get the text value
	    var targetId = this.getAttribute("alt");
	    var string = this.value;
	    if(langTemplates[targetId] != null){
		    for(key in langTemplates[targetId]){
				// alle {key} in dem resourcetext ersetzen
		    	string = string.replace("{"+key+"}", langTemplates[targetId][key]);
		    }
			langTemplates[targetId]['resText'] = string;
	    }
		
		$("#"+targetId).text(string);
		
	});
}

function languageSwitcher(){
		
	// define language specific url-part translations
	// if a langauge is not defined here but the label exists the
	// NavigateUrl of the asp:menuItem is used. Default is /{language} -> /en-us
	var langs = new Array();
				
	langs['Deutsch'] = new Object();
	langs['Deutsch']['lang'] = 'de-de';
	langs['Deutsch']['pages'] = 'seiten';
	
	langs['English'] = new Object();
	langs['English']['lang'] = 'en-us';
	langs['English']['pages'] = 'pages';
	
	// regex to extract language specific parts out of the url
	var regexLang = new RegExp("(de-de|en-us)", "i");
	var regexPages = new RegExp("(seiten|pages)", "i");
	
	for(key in langs){
		var lang = langs[key];
		// get menu-item-link of specified language
		var langCell = $("#zz3_LanguageSwitchn0Items tr[title='"+key+"'] table td a");

		if(langCell != null){
		
			// modify link to fit the language
			var langUrl = location.href;
			
			langUrl = langUrl.substring(0, langUrl.lastIndexOf("/")-1);
			langUrl = langUrl.substring(0, langUrl.lastIndexOf("/"));
			langUrl = langUrl.replace(regexLang, lang['lang']);
			langUrl = langUrl.replace(regexPages, lang['pages']);

			langCell.attr("href", langUrl);
		}
	}
}

function searchHelper(){

	var labelText = language == "en-us" ? "Search" : "Suche";
	var txtSearch = $(txtSearchId);
	if(txtSearch.length > 0){	

		// set current searchterm to textbox
		// if no searchterm in url, assign eventhandler to set fieldvalue
		if(getURLParam("k") != ""){
			labelText = getURLParam("k");
		}else{					
			txtSearch.mouseup(function clear(){
				txtSearch.select();
				});
		}
		
		txtSearch.val(labelText);				
	}
}

function getViewMode(){
		
    if(location.host.indexOf("imtmedical") > -1 && location.host.indexOf(":9470") < 0){
	    return "public";
    }else{				
	    if($("#qaCheckin_anchor").length > 0){
		   return "edit";
	    }else{
	       return "author";
	    }
    }			
}

function linkFixer(){
	
	var links = $("a[href]");
	
	for(var i=0;i<links.length;i++){
	
		var link = links[i];
		var attrVal = link.getAttribute("href");	

		if(attrVal.indexOf("webstore.imtmedical") > -1){
			link.setAttribute("target","_blank");
		}

		if(attrVal.indexOf("__PageLib__") > -1){
			link.setAttribute("href", attrVal.replace(/__PageLib__/g, langTemplates['cfgPageLib']['resText']));
		}
		
		if(attrVal.indexOf("imtmedical.com:9470") > -1 && getViewMode() == "public"){
			link.setAttribute("href", attrVal.replace(/imtmedical.com:9470/g, "www.imtmedical.com"));
		}
	} 
	
	$("a[title~='Quotation'], a[title~='Angebot']").click(function (e){
		return popup($(this).attr('href'), "quotationform", "width=480,height=750,scrollbars=yes,resizable=yes");
	});
}

function renderBoxes(){
	
	if(viewMode != 'edit'){
		$("div.box").each(function(i){
		
			//var this = $(this);
			var id = this.getAttribute("id");
			if(id != ''){
				/*selector, borders, outher, inner, border type/color*/
				Rounded("div#"+id,"top","transparent","#EFEFEF", "border #D7D7D7");
				Rounded("div#"+id,"bottom","transparent","white", "border #D7D7D7");
			}
		});
	}
}

var win = null;
function popup(mylink, windowname, options){
	if (!window.focus)return true;
	var href;
	if (typeof(mylink) == 'string')
	   href=mylink;
	else
	   href=mylink.href;

	if(win == null){
		win = window.open(href+"#", windowname, options);
	}	
	
	win.focus();	

	return false;
}


function bzSlider(sliderId, settings) {

	this.thumbs 		= null;				// array of link elements with a href attribute like: href="#pathToImageBig" title="imageDescriptionToShow">link1<\a> or &lt;img src="thumbNailImage" />
	this.description	= null;	    		// div that shows description (title attribute of imageSlider link element)
	this.tmSlider 		= null;				// timerObject if interval > 0
	this.clickHandler 	= null;			    // developers must set a method that handles clicks of their thumbs, textlinks and returns the link element with the href attribute containing the bigImage Path
	this.sliderId 		= sliderId;
	this.scCurrentIndex = 0;
	
	this.settings = {
		interval: 0,// ms to wait before loading next image
		useDescription: false // use the title attributes of link elements as description
	};
	
	this.create = function (settings){
	        
			// sliderId not match
	        if($(sliderId).length == 0){ return false; }
			
			// extend / overwrite existing settings
			if(settings)
				$.extend(this.settings, settings);
	        
	        // get collections
			this.thumbs			= $(sliderId+" .imageSlider a");
			this.scImages		= $(sliderId+" .imageBigContainer li");
			this.scDescription	= $(sliderId+" .imageBigDescription");

			// order elements
			for(var i=0; i<this.scImages.length;i++){
				var li = $(this.scImages[i]);
				li.css("z-index", String(this.scImages.length-i));
				li.hide();
			}
			
			// handle the click event from imageSlider elements
			for(var i=0; i<this.thumbs.length;i++){
				var link = this.thumbs[i];
				// register event
				jQuery.event.add(link, "click", this._clickHandler.bind(this));
			}
						
			// start scheduled slideshow if interval given, otherwise show first image
			if(this.settings.interval > 0){
			    if(this.thumbs.length > 1){			
				    this.autoSlideImages(this.scCurrentIndex);
				}else{
				    this.showImage(this.thumbs[this.scCurrentIndex]);
				    this.thumbs.hide();
				}
			}else{
				this.showImage(this.thumbs[this.scCurrentIndex]);			
			}
			
			return this;
	}
	
	this._clickHandler = function(ev){
			// stop scheduled slideshow
		    if(this.tmSlider != null){
			    clearTimeout(this.tmSlider);
		    }

		    if(typeof(this.clickHandler) != "function"){
			    alert("Define the function that handles clicks from link elements in #imageSlider. p.e.: objSlider.clickHandler = function (ev){ return ev.target };");
		    }			
		    // show clicked image
		    this.showImage(this.clickHandler(ev));
	}
	
	this.showImage = function(link){
	
			// only go on if link is a html element			
			if(link == undefined || link == null){ return; }
			
            var href = String(link.attributes["href"].nodeValue);
            var scNewIndex = Number(href.substring(href.indexOf("#")+1));
			
			$(this.scImages[this.scCurrentIndex]).fadeOut(2000);
			$(this.scImages[scNewIndex]).fadeIn(2000);
			this.scCurrentIndex = scNewIndex;
			
			// show description if title exists and its declared to use it.
			if(this.settings.useDescription == true && link.attributes["title"] != null){
				var newImageDesc = ""+link.attributes["title"].nodeValue;
				this.scDescription.css("display", "block");
				this.scDescription.text(newImageDesc);
			}else{
				this.scDescription.css("display", "none");
			}
	}	

	this.autoSlideImages = function(imageIndex){
			
		    this.showImage(this.thumbs[imageIndex]);
		    // begin with first again if last image showing
		    var nextIndex = (imageIndex == this.thumbs.length-1) ? 0 : imageIndex+1; 
			
		    // settimeout would handle the called function in global context (not the object that called). this means that this revers to window instead of the calling object
		    // but we can invoke the method manaully with a different scope passed by as argument Function.Prototype.bind(this)    
		    this.tmSlider = window.setTimeout(function(){ this.autoSlideImages(nextIndex); }.bind(this), this.settings.interval);					
	}
}

function thumbOpenInit(){
    
    if(viewMode == "edit") return;

    // this keywords are at the beginning in title attribute of link elements. usage:
    // <a href="www.com" title="pdf"><img src="thumbPreview.jpg" alt="Open pdf in new window" /></a>
    // <a href="www.com" title="thickbox This text describes the picture in the lightbox"><img src="thumbPreview.jpg" alt="Click to zoom image" /></a>
    var keywords = new Array("thickbox", "pdf");

    for(keyword in keywords){
        var key = keywords[keyword];
	    
	    thumbOpen(key);
	}   
}

function thumbOpen(k){

    // give the use a feedback that thickbox pictures can be zoomed
    $("a[title~='"+k+"']").mouseover(function(e){
		var _key = k;
	    // remove thickbox from the beginning of the title attribute value
	    // this _keyword is entered when authoring with ECMS 
	    // and is used to identifies all images that can be zoomed
	    var title = this.getAttribute("title");
	    if(title.indexOf(_key) > -1){
	        this.setAttribute("title", title.substr(_key.length).trim());
	    }
		
	    var thumb = $(this).find("img[class!='"+_key+"Open']")[0];		
	    var zoomImageWidth;
	    var zoomImageHeight;
	    var zoomImagePath;  		
		
		switch(_key){
		    
		    case "pdf":		    
		        zoomImageWidth = 16;
	            zoomImageHeight = 16; 
	            zoomImagePath = "/SiteCollectionImages/Layout/pdf16.gif";  
		    break;
		    
		    case "thickbox":  		    
	            zoomImageWidth = 30;
	            zoomImageHeight = 30;   
	            zoomImagePath = "/SiteCollectionImages/Layout/loupe.png";         		 		    
		    break;    		    
		}
		
		var imageLeft = parseInt(thumb.width/2,10)+parseInt(zoomImageWidth/2,10);
        var imageTop = parseInt(thumb.height/2,10)-parseInt(zoomImageHeight/2,10);
		
	    $(this).append("<img class='"+_key+"Open' src='"+zoomImagePath+"' alt='Click for zoom' style='position:absolute;margin-left:-"+imageLeft+"px;margin-top:"+imageTop+"px;z-index:90' />");
    });
	
    $("a[title~='"+k+"']").mouseout(function(e){	
        var _key = k;
        
        var relTarg = e.relatedTarget || e.fromElement;
	    
        if(relTarg.className != _key+"Open"){	        
            $(this).find("img."+_key+"Open").remove();
        }
    });	 
}


/*
    JS Prototypes
*/
// source:  http://groups.google.com/group/JavaScript-Information/browse_thread/thread/75ecf518fb4b145f
Function.prototype.bind = function(scope){
	var method = this;
	return function(){
		return method.apply(scope, arguments);
	}
}	

String.prototype.format = function(){
    var str = this;
    for(var i=0;i<arguments.length;i++)
    {
        var re = new RegExp('\\{' + (i) + '\\}','gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
}	

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };


/*
Plugins
*/

jQuery.fn.textLimiter = function(){
    return this.each(function(){            
            $(this).bind("keyup", function(){
                var maxLength     = this.getAttribute('maxlength') + this.getAttribute('maxlen');
                var currentLength = this.value.length;
                if(maxLength != null && currentLength >= maxLength) {
                    this.value = this.value.substring(0, maxLength);
                } else { }
            });
    });
};