/**
 * Enkel function för att översätta nycklar i Java script.
 *
 * @package Skipass
 */
AppLanguage = Class.create();
AppLanguage.prototype =
{
    initialize: function(site,lang)
    {
      this.site = site;
      this.siteTag = site.toUpperCase().substr(0,1);
      this.lang = lang;

      this.r2Texts = $H();
      this.shortTexts = $H();
      this.requestMissing = false;
    },
    cacheR2Texts: function(r2texts)
    {
      var me = this;
      r2texts.each(function(pair) { me.r2Texts[pair.key] = pair.value; });
    },
    cacheShortTexts: function(texts)
    {
      var me = this;
      texts.each(function(pair) { me.shortTexts[pair.key] = pair.value; });
    },
    getText: function(key,domain)
    {
      if(domain && domain == "R2")
          return this._getR2Text(key);
      else
          return this._getShortText(key);
    },
    _getShortText: function(k)
    {
      var t = this.shortTexts[k];

      if(t)
          return t;
      else
          return this._missing(k);
    },
    _getR2Text: function(k)
    {
       // OK, fix key
       if(k.substr(0,3) == 'TXT')
       {
         var firstChoice = "TXT" + this.siteTag + k.substr(4);

         var t = this.r2Texts[firstChoice];
         if(t)
             return t;
       }

       var t = this.r2Texts[k];

       if(t)
           return t;
       else
           return this._missing(k,'R2');
    },
    _missing: function(k,domain)
    {
      if(this.requestMissing)
      {
          this.callResult = "";

          var p = $H({site: this.site, lang: this.lang,key: k, domain: domain });
          new Ajax.Request('/app/projects/common/templates/applang/api/gettext.php',{method: 'get',parameters: p,asynchronous: false,onSuccess: this.onSuccess.bind(this)});
          
          if(this.callResult.length > 0)
          {
            if(domain && domain == "R2")
                this.r2Texts[k] = this.callResult;
            else
                this.shortTexts[k] = this.callResult;
                
            return this.callResult;
          }
      }
      alert('Missing: ' + k + domain);
      return k;
    },
    onSuccess: function(transport)
    {
        this.callResult = transport.responseText;
    }
};
/*
Ex:
var bAppLang = new AppLanguage('are','sv');

bAppLang.cacheShortTexts($H({one: 'ett', two: 'två'}));
bAppLang.cacheR2Texts($H({TXTABOK1: 'Åre boka1', TXTXBOK1: 'Common boka1'}));

alert(bAppLang.getText('one')); => ett
alert(bAppLang.getText('TXTXBOK1')); => Åre boka1

*/

showInlineHelp=function(txtkey,txttitle,site,lang,titlecat,targetObject)
{
  	if(!titlecat)
    	titlecat = "";
  		
	// IP_show(this.title,'/app/projects/common/templates/help/inlineMain.php?KeepThis=true&txtKey=' + txtkey + '&titleKey=' + txttitle + '&titleCat=' + titlecat + '&bLang='+lang + '&bSite='+site +'&TB_iframe=true&height=400&width=300');
	
	// Do we know which link that was clicked?
	if (targetObject != null)
	{
		if(null !== targetObject && 'object' == typeof(targetObject))
		{
			// We got an object so we do not have to perform a lookup
		}
		else
		{
			targetObject = document.getElementById(targetObject);
		}
	}
	
	
	// We did not receive an object reference or ID so we have to find out which element that triggered the event
	if (targetObject == null)
	{
		// Let's try to find out which element was clicked by searching for an element that currently has focus:
		var myFocusElements = $jq('a:focus');
		
		if (myFocusElements.length >0) 
		{	
			targetObject = myFocusElements[0];
		}
		else
		{
			// TODO: Webkit can not find the object which currently has focus
			
		}
	}
	
	txttitle = escape(txttitle).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
	
	JT_show('/app/projects/common/templates/help/inlineMain.php?KeepThis=true&txtKey=' + txtkey + '&titleKey=' + txttitle + '&titleCat=' + titlecat + '&bLang='+lang + '&bSite='+site +'&TB_iframe=true&encoding=UTF-8',targetObject,txttitle)

}


/*
 * JTip
 * By Cody Lindley (http://www.codylindley.com)
 * Under an Attribution, Share Alike License
 * JTip is built on top of the very light weight jquery library.
 */

var toolTipTimer = false;

 showToolTip=function(evt,title,ingress)
 {
        if(evt == null)
	    evt = window.event;
	    
	if(evt.currentTarget)
		obj = evt.currentTarget;
	else if(window.event.srcElement)
		obj = evt.srcElement; // IE

    JT_hover ('<b>' + title + '</b> ' + ingress, getAbsoluteLeft(obj), (getAbsoluteTop(obj) + obj.clientHeight + 2) );
 }

 hideToolTip=function(evt)
 {
	clearTimeout(toolTipTimer);
	toolTipTimer = setTimeout("$jq('#JT').remove()", 200);
 }
 
 showToolTipSubarea=function(evt,title,ingress)
 {
        if(evt == null)
	    evt = window.event;
	    
	if(evt.currentTarget)
		obj = evt.currentTarget;
	else if(window.event.srcElement)
		obj = evt.srcElement; // IE

    JT_hover ('<b>' + title + '</b> ' + ingress, getAbsoluteLeft(obj), (getAbsoluteTop(obj) + obj.clientHeight + 22) );
 }

 hideToolTipSubarea=function(evt)
 {
	clearTimeout(toolTipTimer);
	toolTipTimer = setTimeout("$jq('#JT').remove()", 200);
 }


//on page load (as soon as its ready) call JT_init
if(typeof($jq) != 'undefined')
    $jq(document).ready(JT_init);

function JT_init(){
	       $jq("a.jTip")
		   .hover(function(){JT_show(this.href,this.id,this.name)},function(){$jq('#JT').remove()})
           .click(function(){return false});	   
}

function JT_hover (message,clickElementx,clickElementy){
		
		
		
	clearTimeout(toolTipTimer);

	var de = document.documentElement;
	var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var hasArea = w - clickElementx;
	
	/* If the tooltip already is created, refill the current */
	if ($jq('#JT').length > 0)
	{
		$jq('#JT_copy .inner').html(message);
		$jq('#JT').css({left: clickElementx+"px", top: clickElementy+"px"});
	}
	else
	{
		// TODO: flip side if the tooltip is rendered outside the current viewport
		if(hasArea>(164+75))
		{
			$jq("body").append("<div id='JT' class=\"hover\" style='width:"+164+"px'><div id='JT_copy'><div class='inner' style='max-width: 144px'>"+message+"</div></div></div>");//right side
		}
		else
		{
			$jq("body").append("<div id='JT' class=\"hover\" style='width:"+164+"px'><div id='JT_copy'><div class='inner' style='max-width: 144px'>"+message+"</div></div></div>");//left side
		}
		
		$jq('#JT').css({left: clickElementx+"px", top: clickElementy+"px"});
		
		$jq('#JT').mouseenter(function() {
			clearTimeout(toolTipTimer);
		});
		
		$jq('#JT').mouseleave(function() {
			hideToolTip();
		});
		
		$jq('#JT').show();
	}
	

}

function JT_show(url,targetObject,title){
	
	$jq('#JT').remove();
	
	if ((typeof targetObject) == 'string')
		targetObject = document.getElementById(targetObject);
	
	if(title == false)title="&nbsp;";
	var de = document.documentElement;
	var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var hasArea = w - getAbsoluteLeft(targetObject);
	var clickElementy = getAbsoluteTop(targetObject); //set y position
	
	var queryString = url.replace(/^[^\?]+\??/,'');
	var params = parseQuery (queryString);
	//if(params['width'] === undefined){params['width'] = 250};
	/*
	if(params['link'] !== undefined){
		$jq('#' + linkId).bind('click',function(){window.location = params['link']});
		$jq('#' + linkId).css('cursor','pointer');
	}*/
	
	if(hasArea>((params['width']*1)+75)){
		$jq("body").append("<div id='JT' class=\"popup\"><div class=\"top\"><div class=\"inner\"></div></div><div id='JT_copy_padding'><div id='JT_copy'><div class='JT_loader'></div></div></div><div class=\"bottom\"><div class=\"inner\"></div></div><a href=\"javascript:void $jq('#JT').remove()\" class=\"close\"></a></div>");//right side
		var clickElementx = getAbsoluteLeft(targetObject)
	}else{
		$jq("body").append("<div id='JT' class=\"popup\"><div class=\"top\"><div class=\"inner\"></div></div><div id='JT_copy_padding'><div id='JT_copy'><div class='JT_loader'></div></div></div><div class=\"bottom\"><div class=\"inner\"></div></div><a href=\"javascript:void $jq('#JT').remove()\" class=\"close\"></a></div>");//left side
		var clickElementx = getAbsoluteLeft(targetObject);
	}
	
	if($jq.browser.msie)
		clickElementy -= 10;
	
	$jq('#JT').css({left: (clickElementx - 10) + "px", top: clickElementy+"px"});
	$jq('#JT').show();
	
	url += ' #mainContent';
	
	$jq('#JT_copy').load(url);
}

function getElementWidth(objectId) {
	x = document.getElementById(objectId);
	return x.offsetWidth;
}

function getAbsoluteLeft(o) {
	// Get an object left position from the upper left viewport corner
	if (o == null)
		return 0;
	
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	return oLeft
}

function getAbsoluteTop(o) {
	
	if (o == null)
		return 0;
	
	// Get an object top position from the upper left viewport corner
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	return oTop
}

function parseQuery ( query ) {
   var Params = new Object ();
   if ( ! query ) return Params; // return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function blockEvents(evt) {
              if(evt.target){
              evt.preventDefault();
              }else{
              evt.returnValue = false;
              }
}

function toggleAccomodationOffers() { 
    if ($jq("#accomodationOffersContainer:visible").length > 0)
    {
        $jq("#accomodationOffersContainer").slideUp(); 
        $jq(".offersheading.collapsible").addClass('collapsed');
    }
    else 
    {
        $jq("#accomodationOffersContainer").slideDown();
        $jq(".offersheading.collapsible").removeClass('collapsed'); 
    }
}


function toggleAccShare() {
	if ($jq(".accShareWrapper").is(":hidden"))
	{
		$jq(".accShareWrapper").stop().slideDown();
		$jq("a.accShareLink").fadeTo(100, 0.5);
	}
	else
	{
		$jq(".accShareWrapper").stop().slideUp();
		$jq("a.accShareLink").fadeTo(100, 1);
	}
}

