/**
 * Script for Global Elements
 * 
 * 
 * @project   Mister Spex
 * @version   20100402
 * @author    Bjoern Kropp, Peter Klein
 * @requires  jQuery 1.4.2
 * @requires  inputLabel-Plugin v0.2
 */
 
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
	{
	x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
	y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
	x=x.replace(/^\s+|\s+$/g,"");
	if (x==c_name)
		{
		return unescape(y);
		}
	}
}
function NavGlobalShow() { $("div.row", this).show(); }
function NavGlobalHide() { $("div.row", this).hide(); }


/**
 * Funktionen für Newsletteranmeldung
 * @author M.Helsing
 * @2011/10/26
 */
function NewsletterControl(action)
{
  // Close NewsletterLayer
  if( action == 'close' )
  {
    $('#NewsletterEntry, #facebox_overlay').fadeOut('slow');
    return false;
  }
  
  // Check NewsletterLayer exists
  // if dont exists: generate & open
  if( !$('#NewsletterEntry').size() )
  {
    var Newsletter = '';
    Newsletter += '<div id="NewsletterEntry">';
    Newsletter += '<a href="#" id="NewsletterClose" title="Close"><span>Close Window</span></a>';
    Newsletter += '<iframe frameborder="0" scrolling="no" width="840" height="420" src="/newsletter.html"></iframe>';
    Newsletter += '</div>';
    
    // check exists overlay
    (!$('#facebox_overlay').size() ? Newsletter += '<div id="facebox_overlay" class="facebox_overlayBG"></div>' : $('#facebox_overlay').fadeIn() );
    
    $('#MisterSpex').prepend(Newsletter);
    
    $('#NewsletterClose, #facebox_overlay').click(function(el)
    {
      el.preventDefault();
      $('#NewsletterEntry, #facebox_overlay').fadeOut('slow', function()
      {
        $(this).remove();
      });
    });
    
    $('html,body').animate({scrollTop: 'MisterSpex'}, 1000);
  }
  // if exits open
  else
  {
    $('#NewsletterEntry, #facebox_overlay').fadeIn();
  }
}

/**
 * NL-Trackingabschluss
 */
function sendNlTracking(referer)
{
  if( referer != 'false' )
  {
    wt.sendinfo(
    {
      linkId:'newsletter',
      customClickParameter:{3:referer}
    });
  
    // Parameter löschen
    $.ajax({
      type: "GET",
      url: "/sessionkeyvalue.y?Key=NewsletterTracking&Value=false"
    });
  }
}

/**
 * Verhindert das Absenden
 * bevor Gender gesetzt wurde
 */
function DontSubmitOnEnter(e) {
  var ENTER_KEY = 13;
  var code = "";

  if (window.event) { // IE
    code = e.keyCode;
  }
  else if (e.which) { // Netscape/Firefox/Opera
    code = e.which;
  }
  if (code == ENTER_KEY) {
    return false;
  }
}

// Layer für NL-Popup erzeugen
function createLayer()
{
  var cookie_wert = getCookie('Newsletter');  
  var cookie_wert_langzeit = getCookie('NewsletterConfirm');
  
  // Wenn kein Cookie
  if(cookie_wert == undefined && cookie_wert_langzeit == undefined)
  {
    NewsletterControl('open');
    document.cookie = 'Newsletter=open; path=/'; // Cookie setzen
  }
}
/** END NEWSLETTER **/



/**
* cleanString
* Umlaute in einfache Vokale umwandeln, andere Sonderzeichen in _ umwandeln
* @author S. Wittmütz
*/
function cleanString(str)
{
  var str = str
    .replace(/[\u00e0\u00e1\u00e2\u00e3\u00e4\u00e5\u00e6]/g, 'a') // Alle Versionen von "a" in "a" umwandeln, folgend für die anderen Vokale
    .replace(/[\u00e8\u00e9\u00ea\u00eb]/g, 'e')
    .replace(/[\u00ec\u00ed\u00ef]/g, 'i')
    .replace(/[\u00f2\u00f3\u00f4\u00f5\u00f6]/g, 'o')
    .replace(/[\u00fc\u00fb\u00f9\u00fa]/g, 'u')
    .replace(/[^A-Za-z0-9\-_]/g, '_') // Alle Sonderzeichen durch Unterstrich ersetzen
    .replace(/[_]$/,''); // Unterstrich am Ende entfernen
  return str;
}

$(document).ready(function() {
  
  $('#affiliatelogos a, .external,.figure.payments a.paypal, .figure .dhl, .shipping-information, #HomeMap a').each(function(){
    $(this).attr("target", "_blank")
  });

  /** Show/Hide Subnavigation */
  jQuery('#NavGlobal li:not(li li)').bind({
    mouseover: function() {
      $(this).addClass('active');
       $('a:first' ,this).addClass('hover');
    },
    mouseout: function() {
      $(this).removeClass('active');
      $('a:first' ,this).removeClass('hover');
    }
  }); 


  /** Active-Focus-States for #Search */
  jQuery('#SearchEngineInputField').bind({
    focus: function() {
      $('#CartSummary, #Hotline').removeClass('active');
      $('#Search').addClass('active');
    },
      blur: function() {
        window.setTimeout(function() { $('#Search').removeClass('active'); }, 100);  //otherwise no searchengine events can happen onclick! stopped by class change!
      }
  });


  /** Set Autocomplete-Attribute for #Search */
  $('#SearchEngineInputField').attr('autocomplete', 'off');
  
  /** Submit button disable for #Search, if no content for input field*/
  $('#Search input[type="submit"]').attr('disabled','disabled');
  $('#SearchEngineInputField').keypress(function(){
    if($(this).val() != ''){
      $('#Search input[type="submit"]').removeAttr('disabled');
    }
  });


  /** Set Trigger for #Hotline */
  jQuery('#Hotline h3 a').bind({
    click: function() {
      $('#CartSummary').removeClass('active');
      $('#Hotline').toggleClass("active");
      /** Tracking if click shows hotline panel*/
      if ($('#NavUtilities .panel').css('display')=='block')
      {
        var pageTracker = _gat._getTracker("UA-19603091-1");
        pageTracker._trackEvent("Callback","Ansicht");
        wt.sendinfo({linkId:'flyout.rueckruf',customClickParameter:{5:'Ansicht'}}); //Webtrekk
      };
      return false;
    }
  });
  
  /** GA tracking for mailto-link*/
  jQuery('#Hotline p#eMail a').click(function(){
    var pageTracker = _gat._getTracker("UA-19603091-1");
    pageTracker._trackEvent("Callback","Mailto"); 
    wt.sendinfo({linkId:'flyout.rueckruf',customClickParameter:{5:'Mailto'}}); //Webtrekk
  });

  /** Set Trigger for #CartSummary */
  jQuery('#CartSummary h3 a').bind({
    click: function() {
      $('#Hotline').removeClass('active');
      $('#CartSummary').toggleClass("active");
      if ($('#Minibasket').css('display')=='block')
      {
        wt.sendinfo({linkId:'flyout.minibasket',customClickParameter:{6:'Ansicht'}}); //Webtrekk
      };
      return false;
    }
  });


  /** Set Trigger for #CallbackClose-Button */
  jQuery('#CallbackClose').bind({
    click: function() {
      $('#Hotline').removeClass('active');
    }
  });

  /** 
   * Set Input-Labels for #SearchInput + #CallbackForm 
   * 
   * @note:     $("#SearchInput").inputLabel("z.B. Oakley");
   */

  $("#SearchEngineInputField").inputLabel();
  $("#CallbackForm input[type='text'], #CallbackForm select").inputLabel();

  

  $("#CallbackSubmit").bind({
    click: function() {  
      //$('.error').hide();  
      var phone = $("input#CallbackPhone").val();  
      var name = $("input#CallbackName").val();
      var country = $("select#BillingAddressCountry").val();
      var email = $("input#CallbackEmail").val();
  
      if (phone == ""){              
         //$("label#phone_error").show();  
         $("input#CallbackPhone").focus();  
         return false;                 
      }            
  
      if (name == "" || name == "Your name*" || name == "Name"){                              
         //$("label#name_error").show();  
         $("input#CallbackName").focus();  
         return false;                 
      }              
  
      if (phone != "") {
  
        var countEmptySpaces = 0;
                                
    
        for (var i = 0; i < phone.length; ++i)
        {
            if(phone.charAt(i) == " " || phone.charAt(i) == "-" || phone.charAt(i) == "+" || phone.charAt(i) == "/" || phone.charAt(i) == "(" || phone.charAt(i) == ")")
            { 
              countEmptySpaces++;
      
          	if(countEmptySpaces == phone.length) 
          	{   
            	//$("label#phone_error").show();  
            	$("input#CallbackPhone").focus();  
                return false;
          	}
            else 
            {
            	continue;
            }
              
        }
                            
            
            if(phone.charAt(i) <"0" || phone.charAt(i) > "9")
            {
              //$("label#phone_error").show();  
              $("input#CallbackPhone").focus();  
                 return false;
            }
           
        }
      }
      if (email != '' && email!='Your e-mail') {
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if (!email.match(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i)){
          $("#eMailError").remove();
          $("input#CallbackEmail").after('<span id="eMailError" style="color:#bb0000; font-size:12px; display:block; float:left;">Your e-mail adress is incorrect</span>');
          $("input#CallbackEmail").focus();
          return false;
        } else {
          var mailString = '&email='+email;
        }
      }
      if(email=='' || email=='Your e-mail') {
        var mailString = '';
      }
      var dataString = 'phone=' + phone + '&' + 'name=' + name + mailString +'&Subject=Callback&To=service@misterspex.co.uk' + '&country=' + country;
      //alert (dataString);
      $.ajax({
        type: "POST",
        url: "/formmailer.y",
        data: dataString,
        // TODO wartet auf success vom formmail
        success: function() {
          $('#CallbackService').html("<div id='message'></div>");
          $('#message').html("<h2 style='color:#fff;font-size: 1.1em; line-height:12px; margin-bottom:0.5em;'>Thank you for your contact details!</h2>");
          $('#message').append("<p>We will call you back as soon as possible.</p>");
          $('#message').append('<div class="controls ctrlright noMargin"><button type="button" name="CallbackClose" id="CallbackClose"><strong><span>Close</span></strong></button></div>');
          jQuery('#CallbackClose').bind({
            click: function() {
              $('#Hotline').removeClass('active');
            }
          });
          // Google Analytics fake pageview
          var pageTracker = _gat._getTracker("UA-19603091-1");
          pageTracker._trackEvent("Callback","Gesendet");
          wt.sendinfo({linkId:'flyout.rueckruf',customClickParameter:{5:'Gesendet'}}); //Webtrekk
          //.hide()
          //.fadeIn(1500, function() {
          //$('#message').append("<img id='checkmark' src='images/check.png' />");
          //});
        }
      });
      return false;
    }
  });  
  
  $('#BookmarkUrl,#kundenlink').val(window.location.href);
  jQuery('#BookmarkUrl,#kundenlink').bind({
    click: function() {
      this.focus();
      this.select();
    }
  });
  
  
  // init facebox only when facebox links are present in dom
  if ( $("a[rel^='facebox']").length > 0 && $.facebox == undefined) {
    // reload facebox js since it has not beed loaded in the markup
    $.getScript('/js/jquery-plugins/facebox.js', function() {
      initFacebox();
    });
  } else if ( $("a[rel^='facebox']").length > 0 ) {
    initFacebox();
  }
  
  //switch languages
  $('#NcLanguage').click(function(){
	  $(this).children('ul').toggleClass('opened');
	});
	
	/*
   * jQuery replaceText - v1.1 - 11/21/2009
   * http://benalman.com/projects/jquery-replacetext-plugin/
   * 
   * Copyright (c) 2009 "Cowboy" Ben Alman
   * Dual licensed under the MIT and GPL licenses.
   * http://benalman.com/about/license/
   */
  (function($){$.fn.replaceText=function(b,a,c){return this.each(function(){var f=this.firstChild,g,e,d=[];if(f){do{if(f.nodeType===3){g=f.nodeValue;e=g.replace(b,a);if(e!==g){if(!c&&/</.test(e)){$(f).before(e);d.push(f)}else{f.nodeValue=e}}}}while(f=f.nextSibling)}d.length&&$(d).remove()})}})(jQuery);
	//Replace Levis Branding Text
	$('*').each(function(){
      $(this).replaceText(/Levis/, 'Levi´s®');
    });

}); // end $(document).ready()

function initFacebox() {
  $("a[rel^='facebox']").each(function(index){
    if ( $(this).attr('rel').search("faceboxIframe") == 0 ) {
      $(this).click(function (e) {
          e.preventDefault(); 
          $.facebox({ 'iframe' : $(this).attr('href'), 'rel' : $(this).attr('rel') }); 
      });
    } else {
      $(this).facebox();
    }
  });
  /*$("a[rel^='facebox']:not(a[rel!='faceboxIframe'])").facebox();
  
  $("a[rel^='faceboxIframe']").each(function(index){
    $(this).click(function (e) { 
        e.preventDefault(); 
        $.facebox({ 'iframe' : $(this).attr('href') }); 
    });
  })*/;
  
  $('.close.facebox, .lightbox.colors').hide();
  getCloseButton();
  
  
  if($('#AddThis'))
  {
    
    //Show AddThis Buttons
    $('#AddThis').show();
    $('#AddThis a img').css("display", "inline-block");
    
    /*var addThisLoc = (location.href.indexOf('https') == 0 ? 'https://secure.' : 'http://s7') + '.addthis.com/js/250/addthis_widget.js'
    $.ajax({
       url: addThisLoc,
       dataType: 'script',
       success: function(){
          window.addthis_config = {
             ui_language: "de", 
             data_ga_tracker: "pageTracker", 
             ui_use_addressbook: "true", 
             data_track_linkback: "true"
          }
        }
      });
    */
  }
}

// show close button for facebox
function getCloseButton(){
  window.setTimeout(function(){
    $('.close.facebox').fadeIn(1000);
  }, 2000)
}


/**
 * CookieHandler
 * Newslettertracking
 * @author M.Helsing / P.Klein
 */
function CookieHandler()
{
  this.setCookie = function (name, value, seconds)
  {
    if (typeof(seconds) != 'undefined')
    {
      var date = new Date();
      date.setTime(date.getTime() + (seconds*1000));
      var expires = "; expires=" + date.toGMTString();
    }
    else
    {
      var expires = "";
    }

    document.cookie = name+"="+value+expires+"; path=/";
  }

  this.getCookie = function (name)
  {
    name = name + "=";
    var carray = document.cookie.split(';');

    for(var i=0;i < carray.length;i++)
    {
      var c = carray[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }

    return carray; // null;
  }

  this.deleteCookie = function (name)
  {
    this.setCookie(name, "", -1);
  }
}

/**
 * Auslesen von URL-Paramentern
 * @author M.Helsing
 * ACHTUNG: Diese Funktion funktioniert nur aus einem iFrame heraus
 */
function getUrlVars()
{
  var vars = [], hash;
  var hashes = window.parent.location.href.slice(window.parent.location.href.indexOf('?') + 1).split('&');
  for(var i = 0; i < hashes.length; i++)
  {
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
  }
  return vars;
}

/**
 * Function initFacebook
 * set the page-parameters
 */
function initFacebook(ProductNo)
{
  if( $('#fb-root').size() && !$('meta[property=og:image]').attr('content') )
  {
    var header = "";
    if(ProductNo)
    {
      header += '<meta property="og:image" content="http://d26hhearhq0yio.cloudfront.net/content/misterspex/produkte/grafiken/'+ProductNo+'_a5.jpg">\n';
      header += '<meta property="og:type" content="product">\n';
    }
    header += '<meta property="og:title" content="'+document.title+'">\n';
    header += '<meta property="fb:admins" content="1515484293">\n';
    header += '<meta property="fb:app_id" content="150053191678545">';
  
    $('head').prepend(header);
    
    (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/all.js#appId=150053191678545&xfbml=1";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
  }
}


/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(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);

