﻿//this is core javascript file for the draka communication website
//this file needs to store basical "design" scripts


function swapImage(idStatus){
	if(idStatus==0){
		document.arrow_profile.src ="arrow_hover.png";
	} else if(idStatus==1){
		document.arrow_profile.src ="arrow_select.png";
	} else if(idStatus==2){
		document.arrow_profile.src ="arrow.png";
	}
}

// Usage:
// onkeypress="javascript:return Draka_FireDefaultButton(event, 'ctl00_SPWebPartManager1_DrakaProductTopFinder1_ctl00_btnSearch')

function Draka_FireDefaultButton(event, target) 
{ 
    if (event.keyCode == 13) 
    {
        var src = event.srcElement || event.target;
        if (!src || (src.tagName.toLowerCase() != "textarea")) 
        {
            var defaultButton;
            if (!$.browser.msie) 
            {
                defaultButton = document.getElementById(target);
            }
            else 
            {
                defaultButton = document.all[target];
            }
            if (defaultButton && typeof(defaultButton.click) != "undefined") 
            {
                defaultButton.click();
                event.cancelBubble = true;
                if (event.stopPropagation) event.stopPropagation();
                return false;
            }
        }
    }
    return true;
}
// Cookie helper functions
function createCookie(name,value,days) {
    if (days) {
	    var date = new Date();
	    date.setTime(date.getTime()+(days*24*60*60*1000));
	    var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
	    var c = ca[i];
	    while (c.charAt(0)==' ') c = c.substring(1,c.length);
	    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

function SubmitSearchBox(elid,resUrl){
//this function needs to submit search form          
          var del=document.getElementById(elid);//another key
          /*validation for ' " and <> characters (seems to be right?!)*/
          var text = del.value;
          if(!text.match(/^[^""''<>]*$/))
          {
            text = text.replace(/[""''<>]/g,"");
            del.value = text;                                          
          }
          var el=document.createElement("form");
          el.method="get";
          el.action=resUrl && String(resUrl) && String(resUrl).length>0?resUrl:resultUrl;
          //-----is submited by search box-----//
          var inp=document.createElement("input");
          inp.type = "hidden";
          inp.id = "putBySearchButton";
          inp.name = "putBySearchButton";
          inp.value = "1";
          //----------------//
          document.body.appendChild(el);         
          el.appendChild(del);
          el.appendChild(inp);
          el.submit();
}


(function($) {
    $.fn.cookie = function(name, value, options) {
			if (typeof value != 'undefined') { // name and value given, set cookie
				options = options || {};
				if (value === null) {
					value = '';
					options.expires = -1;
				}
				var expires = '';
				if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
					var date;
					if (typeof options.expires == 'number') {
						date = new Date();
						date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
					} else {
						date = options.expires;
					}
					expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
				}
				// CAUTION: Needed to parenthesize options.path and options.domain
				// in the following expressions, otherwise they evaluate to undefined
				// in the packed version for some reason...
				var path = options.path ? '; path=' + (options.path) : '';
				var domain = options.domain ? '; domain=' + (options.domain) : '';
				var secure = options.secure ? '; secure' : '';
				document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
			} else { // only name given, get cookie
				var cookieValue = null;
				if (document.cookie && document.cookie != '') {
					var cookies = document.cookie.split(';');
					for (var i = 0; i < cookies.length; i++) {
						var cookie = jQuery.trim(cookies[i]);
						// Does this cookie string begin with the name we want?
						if (cookie.substring(0, name.length + 1) == (name + '=')) {
							cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
							break;
						}
					}
				}
				return cookieValue;
			}
		};
	
	$.Draka={};
	
	LanguageSelector=function()
	{
		//extend $.Draka With  methods, data to work with Countries,Languages from one place
		var result=$.Draka?$.Draka:{};
		
		result.init=function(region,country,site,obj){
			obj =obj?obj:result;
			
			obj.countries.update(country,null,null);//save cur.country: show c.info
			obj.sites.update(country,site,null,null);//save cur.site
			obj.languages.update(country,site,null,null);//save cur.language:update dropdown
		};
		
		result.languages={
			    selector:'#id_menu_profile,.sub_menu',
				ddselector:'.DpopDownLanguageList',
				generalselector:'.LanguageSelectorContainer',
				init:function(obj){	
					obj =obj?obj:result.languages;
					var my_menu = $(obj.selector);
					my_menu.bind("mouseleave",function(){
							obj.hide(obj);
					});
					
					$(obj.ddselector).bind("click",function(){
						obj.show(obj);
					});
					obj.check(obj);//disable element if it empty					
				},
				show:function(obj){	
					obj =obj?obj:result.languages;
					var my_menu = $(obj.selector);
					my_menu.fadeIn();
				},
				hide:function(obj){
					obj =obj?obj:result.languages;
					var my_menu = $(obj.selector);
					my_menu.fadeOut();
				},
				update:function(country,cursite,obj){
					obj =obj?obj:result.languages;					
					var cnr=$(obj.selector);
						cnr=cnr.length>1?$(cnr[0]):cnr;//get frst element only
						cnr.html('');//clear html
						var i=0;
						$(country.sites).each(function(pos,site){
							if ((!cursite) || (cursite && cursite.id!=site.id)){
								i++;
								var siteel=$("<a title='"+String(country.regiontitle)+", "+String(country.title)+", "+String(site.title)+"' href='"+site.resulturl+"'><img alias='flag' class='flag' src='"+site.langflag+"'/>"+site.langtitle+"</a>");
								siteel.bind('click',function(){
									$.fn.cookie( obj.names.languageCode,site.langcode,{expires:30,path:"/"});
									window.location=site.resulturlraw;
									return false;//to don't use href redirections
								});
								siteel.appendTo(cnr);
							}else{
								//$(obj.generalselector).attr("title",String(country.regiontitle)+", "+String(country.title)+", "+String(site.title));
								$(obj.generalselector).bind("click",function(){
									var s=obj;
								});
							}
						});
					
					obj.check(obj);
				},
				check:function(obj){
					obj =obj?obj:result.languages;					
					var cnr=$(obj.selector);
					if (cnr.find("a").length>0) $(obj.ddselector).show();
					else $(obj.ddselector).hide();
				}
			};
		result.countries={
				selector:'.LanguageSelectorContainer .underlineLink',
				update:function(country,obj){
				        obj=obj?obj:result.countries;				        
						var image=$(obj.selector).find("img");
						image.attr('src',country.imageurl);
						image.attr('alias',country.title);
						//image.attr('title',String(country.regiontitle)+","+String(country.title));
						obj.current=country;
					}
			};
		result.sites={		
				current:null,
				update:function(country,site,obj){
					obj=obj?obj:result.sites;
					obj.current=site;
				}
			};
		
		if (typeof result.languages.init=="function") result.languages.init();
		if (typeof result.countries.init=="function") result.countries.init();
		if (typeof result.sites.init=="function") result.sites.init();
		return result;
	};

	
	
	CountriesPopup=function(){
		var result=$.Draka?$.Draka:{};
		
		result.CountriesPopup=
		{
					width:940,
					selector:"#countries_popupcontainer",
					names:{contryCode:"Conutry",languageCode:"Language"},
					show:function(obj){
						obj=obj?obj:result.CountriesPopup;
						obj.container=$(obj.selector);
						obj.container.fadeIn().css({'width':Number(obj.width)});
						
						var popMargTop = (obj.container.height() + 80) / 2;
						var popMargLeft = (obj.container.width() + 80) / 2;

						 //Apply Margin to Popup
						obj.container.css({'margin-top' : -popMargTop,'margin-left' : -popMargLeft});
						 //Fade in Background
						obj.fade=$('<div id="fade"></div>');
						obj.fade.appendTo($('body')); //Add the fade layer to bottom of the body tag.
						obj.fade.css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies 
						
//						var curcountry=$.fn.cookie(obj.names.contryCode);
//						if (curcountry && curcountry!=''){
//							obj.container.find("a").each(function(pos,el){
//								var elA=$(el);   
//								var ttlA=elA.attr('title');
//								if ((ttlA && ttlA.indexOf(curcountry)>-1))
//									elA.addClass('selected');
//							});
//						}
						return false;
					},
					close:function(obj){
						obj=obj?obj:result.CountriesPopup;
						obj.container.fadeOut(function(){
							obj.container.remove();
						});
						obj.fade.fadeOut(function() {
							obj.fade.remove();  
						});
					},
					save:function(country,obj){
						obj=obj?obj:result.CountriesPopup;
						
						$.fn.cookie( obj.names.contryCode,  country.short, {expires:30,path:"/"});
						
						var curCountrySite=null;
						var cursiteurl=result.sites.url?result.sites.url.toLowerCase():"";
						if (cursiteurl.match("/$")!="/") cursiteurl=cursiteurl+"/";
						var csites=$(country.sites);
						csites.each(function(pos,site){//exect match
							var siteurl=site.resulturlraw.toLowerCase();
							if (siteurl.match("/$")!="/") siteurl=siteurl+"/";
							if (siteurl==cursiteurl) {
								curCountrySite=site;
								return false;//breake
							}
						});
						if (!curCountrySite)
							csites.each(function(pos,site){//relative path, when site path contains current path
								var siteurl=site.resulturlraw.toLowerCase();
								if (siteurl.match("/$")!="/") siteurl=siteurl+"/";
								if (siteurl.indexOf(cursiteurl)>0){
									curCountrySite=site;
									return false;//breake
								}
							});
						if (!curCountrySite)
							csites.each(function(pos,site){//relative path, when site path contains current path
								var siteurl=site.resulturlraw.toLowerCase();
								if (siteurl.match("/$")!="/") siteurl=siteurl+"/";
								if (cursiteurl.indexOf(siteurl)>0){//when site path contains current site path
									curCountrySite=site;
									return false;//breake
								}
							});
						
						if (curCountrySite){//current site in the sites list of the selected country							    
							$.fn.cookie( obj.names.languageCode,curCountrySite.langcode,{expires:30,path:"/"});
							result.countries.update(country,null,null);//save current country
							result.sites.update(country,curCountrySite,null,null);//save current site
							result.languages.update(country,curCountrySite,null,null);//save current language
						} else {//if current site not in the list of the sites for the country
							if (csites.length>0) {
								curCountrySite=csites[0];
								$.fn.cookie( obj.names.languageCode,curCountrySite.langcode,{expires:30,path:"/"});
								result.countries.update(country,null,null);//save current country
								result.sites.update(country,curCountrySite,null,null);//save current site
								result.languages.update(country,curCountrySite,null,null);//save current language
								//we can't redirect first time: it will be done automatically when user navigates to 
								//window.location=curCountrySite.resulturl;//redirection -because result site isnot in the country sites
							}							
						}
						//reload page
						window.location=window.location;
						this.close();
						return false;//to informa browser that href don't need to be used
					}
		};
		
		return result;
	}
	
})(jQuery);



 jQuery(document).ready(function(){
	LanguageSelector();//initialize language selector object
	CountriesPopup();//init countries popup
	
	
    
    jQuery(".downloadPdf").find("a").click(function(){
                var ael=jQuery(this);
                var ahref=ael.attr("href");
                var nl1=ael.attr("navlevel1");
                var nl0=ael.attr("navlevel0");
                
                nl0=nl0?String(nl0):"";
                nl1=nl1?String(nl1):"";
                ahref=ahref?String(ahref):"";
                _gaq.push(['_trackEvent', 'Datasheets '+nl0, 'Download', nl1+'/'+ ahref]);
                jQuery(document.body).append("<div style='display:none;'>url:"+ahref+"; nl0:"+nl0+"; nl1:"+nl1+";</div>");
    });
    
 });
