﻿var _popupLayerClientID = '';
var _currentClassName = '';
var _extraPriceFromBindingGroupsMappingCanBeExecuted = true;

var basketIsAlreadyClicked = false;
var paymentUserLoginAndRegistrationControlFormIsOpened = false;
var paymentUserLoginAndRegistrationControlFormType = 'normal';

var __calculateHeightOfLayerIsClicked = false;
var __calculateHeightOfLayerOriginHeight = '';

function Show(id)
{
    document.getElementById(id).style.visibility = 'visible';
    document.getElementById(id).style.height = 'auto';
    document.getElementById(id).style.width = 'auto';
}

function ShowLayer(jqueryexpression, displayprop)
{
    $(jqueryexpression).css({'display':displayprop})
}

function HideLayer(jqueryexpression)
{
    $(jqueryexpression).css({'display':'none'})
}

function calculateResizePanelHeight(modulename, id, maxitems, offset)
{
    if(!__calculateHeightOfLayerIsClicked)
    {
        var height = $(id).css('height');

        height = height.replace('px', '');
        $(id).css({'height' : height * (maxitems / offset)  + 'px'});
        
        __calculateHeightOfLayerOriginHeight = height;
        __calculateHeightOfLayerIsClicked = true;

        $('.' + modulename + ' .ResizePanel .LoadButton').html('Dölj');
    }
    
    else
    {
        $('.' + modulename + ' .ResizePanel .LoadButton').html('Visa alla');
        
        $(id).css({'height' : __calculateHeightOfLayerOriginHeight  + 'px'});
        __calculateHeightOfLayerIsClicked = false;
    }
}

function AutoWriteFormValueByOtherFormValue(valueclass, targetclass, rule)
{
    var value = $(valueclass).val();
    
    if(rule != undefined)
    {
        if(value.indexOf(rule) != -1)
            $(targetclass).val(value);
            
        else
            $(targetclass).val('');
    }
    
    else
        $(targetclass).val(value);
}

function f(id, frameparent, source)
{
    document.getElementById(id).style.visibility = 'visible';
    document.getElementById(id).style.height = 'auto';
    document.getElementById(id).style.width = 'auto';
    
    var e = document.getElementById(frameparent).getElementsByTagName("iframe"); 
    
    if(e.length > 0)
    {      
        e[0].src = source;
        
        try
        {
          var the_height = e[0].contentWindow.document.body.scrollHeight;
          the_height = (the_height < 380) ? 380 : the_height;
          
          e[0].height=the_height;
          
        }
        
        catch (e){
          e[0].height=500;
        }
    }                
}

function ByteEncode(text)
{
    var toReturn = '';
    
    try
    {
        for (i = 0; i < text.length; i++)
            toReturn += text.charCodeAt(i) + ',';
    }
    
    catch (e) {}

    return toReturn;
}

function getPageWidth() 
{
    var windowWidth;

    if (self.innerWidth) 
      windowWidth = self.innerWidth;
    
    else if (document.documentElement && document.documentElement.clientWidth)
      windowWidth = document.documentElement.clientWidth;
    
    else if (document.body)
      windowWidth = document.body.clientWidth;
    
    return windowWidth
}

function Display(id, isDisplay)
{
    document.getElementById(id).style.display = isDisplay;
}

function OpenHide_Click(id, layer,text) {
    if($(layer).html().length == 0)
    {
        $(layer).html(text);
        $(layer).css({'display':'block'});
    }
    else 
    {
        $(layer).html('');
        $(layer).css({'display':'none'});
    }
}

function DisplayHtmlByMouseCords(classname, html, display)
{
    $('.' + classname).html(html);
    $('.' + classname).css({'display':display});
}

function Hide(id)
{
    document.getElementById(id).style.visibility = 'hidden';
    document.getElementById(id).style.height = '0px';
}

function SetCurrentClassName(currentClassName)
{
    _currentClassName = currentClassName;
}

function ChangeClass(defaultpagepath, modulename, classname, sessionid)
{
    if(_currentClassName.length > 0)
    {
        var o = $('.' + modulename + _currentClassName);
        
        if(o.length > 0)
        {
            o.removeClass();
            o.addClass(modulename + classname);

            _currentClassName = classname;
        }
        
        else
        {
            var o = $('.' + modulename);
        
            o.removeClass();
            o.addClass(modulename + classname);

            _currentClassName = classname;
        }
    }
    
    else
    {
        var o = $('.' + modulename);
    
        o.removeClass();
        o.addClass(modulename + classname);

        _currentClassName = classname;
    }
    
    var url = defaultpagepath + 'SetListTypeHandler/' + sessionid + '/' + _currentClassName + '.do';
    
    $.get(url, function(updateurl) 
    { 
    });
}

function changeUrl(location)
{
    window.location = location;
}

function changeColor(id, color)   
{
    document.getElementById(id).style.color = color;
}

function Disabled(id, isDisabled)   
{
    document.getElementById(id).disabled = isDisabled;
}

function doFastPostBack(id, value)
{
    document.getElementById(id).value = value;
}

function RedirectWindow(url)
{
    window.location = url; 
}

function OpenWindow(url, title)
{
    window.open(url, title);
}

function doParcelTracking(defaulturl, useHiddenField, errorMessage)
{
    var searchStr = '';
    
    $('.ParcelTrackerPanel .Result').html('<div class="Loading">Laddar, vänta...</div>');
    $('.ParcelTrackerPanel .Result').css({'display':'block'});

    if(useHiddenField)
        searchStr = $('.ParcelTrackerPanel .UserName').val();
    
    else
        searchStr = $('.ParcelTrackerPanel .TextBox').val();
    
    $.ajax({ url: defaulturl + 'ParcelSearch/' + searchStr + '.aspx', cache:false, success: function(data)
    {
        if(data.length > 0)
        {
            if(data == 'ERR')
            {
                $('.ParcelTrackerPanel .Result').css({'display':'none'});
                CreateTextLayer(errorMessage);
            }
            
            else
            {
                $('.ParcelTrackerPanel .Result').html(data);
                $('.ParcelTrackerPanel .Result').css({'display':'block'});
                $('.ParcelTrackerPanel .FormPanel').css({'display':'none'});
                
                $('.ParcelTrackerPanel a[rel*=facebox]').facebox();
            }
        }
    }});
}

function openLinkByPopupByUrl(modulename, url, externalmoduleurl, externalmoduleid)
{
    $.ajax({ url: url, cache:false, success: function(data)
    {
        if(externalmoduleurl != '')
        {
            $.get(externalmoduleurl, function(externaldata) 
            {
                $('.' + externalmoduleid + 'Panel').html(externaldata);
            });
        }
        
        //$('#facebox .popup .extramessage #data').html('');
        $('#facebox .popup .extramessage').html('<span id="data">' + data + "</span>");
        
        setTimeout("$('#facebox .popup .extramessage').html('');", 2500);
    }});
}

function openModule(modulename, url)
{
    $.ajax({ url: url, cache:false, success: function(data)
    {
        $('.' + modulename + 'Panel').html(data);
        $('a[rel*=facebox]').facebox();
    }});
}

function openModuleByPopupUrl(modulename, url)
{
    $.ajax({ url: url, cache:false, success: function(data)
    {
        $('#facebox .content').html(data);
    }});
}

function openLinkByPopup(defaultpath, modulename, to, p_link_css)
{
    $.ajax({ url: defaultpath + to + '.dhtml', cache:false, success: function(data)
    {
        $('#facebox .content').html(data);
    }});
}

function openLinkByUrl(url)
{
    $.ajax({ url: url, cache:false, success: function(data)
    {
        $('#facebox .content').html(data);
    }});
}

function AddToBasket(defaultPagePath, modulename, sessionid, url)
{
    if(basketIsAlreadyClicked)
        $('.contentPanel .basketloader').remove();

    var b_url = defaultPagePath + modulename + "/" + sessionid + '/GetBasket.do';
    basketIsAlreadyClicked = true;

    $('.contentPanel').append("<div class='basketloader'><a class='a_link' rel='facebox' href='" + b_url + "' /><div>");
    $('.contentPanel .basketloader .a_link').facebox({'staticlinkurl':defaultPagePath + 'Kassa.pay','runfirsturl':url, 'runfirsttext':'Uppdaterar varukorg, vänta...', 'closebuttontext':'<span onmouseover="$(this).addClass(\'Hover\');" onmouseout="$(this).removeClass(\'Hover\');" class="ContiueShopping">Fortsätt handla</span><span onmouseover="$(this).addClass(\'Hover\');" onmouseout="$(this).removeClass(\'Hover\');" class="Pay StaticLink">Gå till kassan</span>'});
    
    setTimeout("$('.contentPanel .basketloader .a_link').click()", 10);
}

function setPopupLayerClientID(id)
{
    _popupLayerClientID = id;
}

function ReceiveServerData(arg, context)
{
    if(arg != null)
    {
        if(arg.match("{popup}"))
        {
            arg = arg.replace(/{popup}/, '');
            document.getElementById(_popupLayerClientID).innerHTML = arg;
        }
        
    else
        window.location = arg;
    }
}

function InactivateImageClick(e)
{
    var evt = e || window.event;
    var errorMessage = "Du kan tyvärr inte att högerklicka på bilder!!!";
    
    $(document).bind("contextmenu",function(e)
    {  
        if($.browser.msie && e.srcElement.tagName == 'IMG' || 
           document.layers && e.which == 3 || 
           document.getElementById && e.which==3 && e.target.tagName=="IMG")
        {
            alert(errorMessage);
            return false;
        }     
        
        return true;  
    });
}

function makeListItemHoverEffect(modulename, current_row_index_classname)
{
    $("." + modulename + " ." + current_row_index_classname).hover(function()
    { 
        /*$(this).click(function() {
            alert('nisse');
        })
        
        $(this).bind('mouseout', function(event) {
            var $target = $(event.target); 
            
            if( $target.is("div") ) { 
                $(this).unbind('click');
                $(this).removeClass('Hover'); 
            } 
        });*/
        
        $(this).addClass('Hover'); 
    })
}

jQuery(document).ready(function($) 
{
  $('a[rel*=facebox]').facebox();
  $('.autoPopupLink').click();
  
    $("input").hover(function(){ $(this).addClass('Hover'); })
    $("input").mouseout(function(){ $(this).removeClass('Hover'); })

    $("textarea").hover(function(){ $(this).addClass('Hover'); })
    $("textarea").mouseout(function(){ $(this).removeClass('Hover'); })
    
    $("select").hover(function(){ $(this).addClass('Hover'); })
    $("select").mouseout(function(){ $(this).removeClass('Hover'); })
   
    InactivateImageClick();
}) 

$(function() {
    var galleries = $('.ad-gallery').adGallery();
    $('#switch-effect').change(
      function() {
        galleries[0].settings.effect = $(this).val();
        return false;
      }
    );
    $('#toggle-slideshow').click(
      function() {
        galleries[0].slideshow.toggle();
        return false;
      }
    );
});
  
$(function(){
    $('ul.AspNet-Menu').superfish({delay: 400});
});

// ---- Jquery plugin //
/* Textboxhelp */
(function($) {
  $.fn.textboxhelp = function(options){
    var defaults = {help: 'Help me!', focuscls:'Hover'};
    var opts = $.extend(defaults, options);
    $(this).val(opts.help);
    $(this).focus(function(){
      var t = $(this).val();
      if(t.length > 0 && t == opts.help)
        $(this).addClass(opts.focuscls).val('');
    }).blur(function() { 
      var t = $(this).val();
      if('' == t)
         $(this).removeClass(opts.focuscls).val(opts.help);
    });
  }
})(jQuery); 

/* HoverIntent */
(function($){
	$.fn.hoverIntent = function(f,g) {
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );
		var cX, cY, pX, pY;

		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				pX = cX; pY = cY;
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		var handleHover = function(e) {
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			var ev = jQuery.extend({},e);
			var ob = this;

			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			if (e.type == "mouseover") {
				pX = ev.pageX; pY = ev.pageY;
				$(ob).bind("mousemove",track);
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			} else {
				$(ob).unbind("mousemove",track);
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		return this.mouseover(handleHover).mouseout(handleHover);
	};
	
})(jQuery);
