//////////////////////////
// jQuery
//////////////////////////

$(document).ready(function() {

  //Search input hint text
  $("#search .query").hint(); //uses hint plugin
  
 // Setup product page Fancybox image viewer (http://fancybox.net/)
   if ($("#product_left .image").length > 0) { //check that image exists   
      $("#product_left .image a").fancybox({
        'titleShow'     : false,
        'transitionIn'	: 'elastic',
        'transitionOut'	: 'elastic'
      });
   }
    
  //cvv example image on checkout
  if ($("#checkout small.cvv").length > 0) { //check that cvv image exists
   $("#checkout small.cvv a").fancybox({
      'titleShow'     : false,
      'transitionIn'	: 'elastic',
      'transitionOut'	: 'elastic'
    });
  }
  
  
  //////////////////////////////////////////////////////
  //show 'buy now' modal window if visitor from motorola.com
  //////////////////////////////////////////////////////
  
  //get referrer  
  var _referrer = document.referrer;
  var _domain_ref = getQuerystring('ref'); //fallback for IE coming from a SWF link
  
  if (_referrer.indexOf('motorola.com') > -1 || _domain_ref == "motorola"){ //only fire if referrer is from motorola.com (or the _domain_ref override is present)
  
      //get current page URL and set abort flag
      var _location = location.href;
      var _abort = false;
    
      if (_location.indexOf('product') > -1){ //only fire if on product page
      
        var _region = _location.split('/'); //explode/spilt URL into array
        _region = _region[3]; // region code *should be* 4th element in the array 
                
        //check region lengh is exactly 2 chars (not foolproof, but will catch the main issues)
        if (_region.length != 2) {
          _abort = true; //region code looks bad - abort!
        }
        
        //get SKU from URL
        var _sku = parseInt(getQuerystring('i'));
        
        //basic check for valid expansys SKU
        if (_sku < 100000 || _sku > 400000 || isNaN(_sku)) { 
          _abort = true; //SKU looks dodgy - abort!
        }
      
        //single SKU test
        /*if (_sku != 198209) {
          _abort = true;
        }*/
        // end test

        //if looking good so far, continue...
        if (!_abort) {
          //build buy link path
          var _domain = "https://www.motorolastore.eu"; // LIVE!
          //var _domain = ""; // testing
          var _buy_link = _domain + "/" + _region + "/p_motorola_checkout.aspx" + "?sbadd=" + _sku;  
          
          //get on page content (title,price,stock,description,image)
          var _title = $('#product_main h1').text();
          var _price = $('#product_main .price strong').text();
          var _stock = $('#prod_head .availability').html();
          var _desc = $('#description p').text();
          var _image = $('#product_left .image img').attr('src');
          
          //Only allow valid regions to use translated image buttons, otherwise just default to English
          switch(_region)
          {
            case "cz":
            case "de":
            case "es":
            case "fr":
            case "gr":
            case "it":
            case "pl":
            case "pt":
              _lang = _region;
              break;
            default:
              _lang = "en";
          }

          //truncate description length if needed
          _desc = truncate(_desc,400);  
            
          //build button path
          var _button_path = "/j/motorola/images/buttons/" + _lang + "/";
          
          //render modal window 
          $.fancybox(
              '<div id="mw"><h2>' + _title + '</h2><ul><li class="price">'+ _price + '</li><li class="stock">'+ _stock + '</li><li class="desc">' + _desc + '</li><li class="image"><img src="' + _image + '" width="162" height="162" alt="' + _title + '"></li><li class="buy"><a href="' + _buy_link + '"><img src="' + _button_path + 'mw_buy-now.png" width="187" height="47" title="" alt="Buy Now"></a></li><li class="continue"><a><img src="' + _button_path + 'mw_continue_shopping.png" width="247" height=47 title="" alt="Continue Shopping"></a></li></ul></div>',
              {
              'autoDimensions':false,'width':900,'height':'auto','overlayColor':'#000','overlayOpacity':'0.6'
              }
            );
        }// end abort
          
        //close window on continue shopping button click
        $('#mw .continue').click(
          function () {
            $.fancybox.close();
          }
        );
      } //end product page check
  } // end motorola.com referrer / QS ref= check  
  
});

// functions / plugins
//truncate source: thetruetribe.com/2008/05/truncating-text-with-javascript/
function truncate(text, length, ellipsis) {if (typeof length == 'undefined') var length = 100; if (typeof ellipsis == 'undefined') var ellipsis = '...'; if (text.length < length) return text; for (var i = length-1; text.charAt(i) != ' '; i--) {length--} return text.substr(0, length) + ellipsis;}

function getQuerystring(key, default_){if (default_==null) default_=""; key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regex = new RegExp("[\\?&]"+key+"=([^&#]*)"); var qs = regex.exec(window.location.href); if(qs == null) { return default_; } else { return qs[1];}  }

//hint source: http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
jQuery.fn.hint = function (blurClass) {
  if (!blurClass) { 
    blurClass = 'blur';
  }

  return this.each(function () {
    // get jQuery version of 'this'
    var $input = jQuery(this),

    // capture the rest of the variable to allow for reuse
      title = $input.attr('title'),
      $form = jQuery(this.form),
      $win = jQuery(window);

    function remove() {
      if ($input.val() === title && $input.hasClass(blurClass)) {
        $input.val('').removeClass(blurClass);
      }
    }

    // only apply logic if the element has the attribute
    if (title) { 
      // on blur, set value to title attr if text is blank
      $input.blur(function () {
        if (this.value === '') {
          $input.val(title).addClass(blurClass);
        }
      }).focus(remove).blur(); // now change all inputs to title

      // clear the pre-defined text when form is submitted
      $form.submit(remove);
      $win.unload(remove); // handles Firefox's autocomplete
    }
  });
};
