/*
 * Zpider eShop JavaScript library
 * ------------------------------- 
 * Copyright (c) 2010 Visma Software AS
 *
 */

// Helper function to get parameters from the query string.
function getUrlParam(paramName) {
   var reParam = new RegExp('(?:[\?&]|&amp;)' + paramName + '=([^&]+)', 'i');
   var match = window.location.search.match(reParam);

   return (match && match.length > 1) ? match[1] : '';
}

// escapes a string that is a part of a URL
function urlescape(str) 
{
   return encodeURIComponent(str);
}
  
// remove the white spaces from the beginning and the end of the input string 
function trim(str)
{
   return (str) ? str.replace(/^\s*|\s*$/g,"") : null;
}

// adds the specified article to shopping cart
function articleToCart(articleNo, amount, animateEl)
{
   $('#shoppingcart').load(
         'main.aspx?zaction=add&module=shoppingcart&artno=' + urlescape(articleNo) + '&amount=' + urlescape(amount),
         function(html, status) {
            if (status == 'success') {
               //$(this).effect("highlight", { color: "#cacaca" }, 1000);
               $(this)
                  .fadeTo(200, 0.3)
                  .fadeTo(500, 1.0);

               if (animateEl) {
                  var elem = $(animateEl);
                  elem
                     .clone()
                     .css({
                        'position': 'absolute',
                        'left': elem.position().left,
                        'top': elem.position().top
                     })
                     .appendTo(elem.parent())
                     .hide("drop", { direction: "up" }, 800, function() { $(this).remove() });
               }
            }
         }
   );
}

// adds the specified article with amount defined by input element
function elementToCart(articleNo, elementId)
{
   var el = document.getElementById(elementId);
   articleToCart(articleNo, (el) ? el.value : 1); 
}

function showDiscountDetails(element, articleno)
{
   if (element) {
      var coords = $(element).offset();
      var details = $('#discountdetails');
      
      if (!details[0]) {
         details = $('<div id="discountdetails" />');
         details.appendTo('body');
      }
      
      details.css({ 
            'display': 'block', 
            'position': 'absolute',
            'width': '150px',
            'left': coords.left + $(element).width() + 5 + 'px',
            'top': coords.top + 'px'
      });

      details.load('main.aspx?module=articlediscount&artno=' + urlescape(articleno)); 
   }
}

function hideDiscountDetails()
{
   var dde = $('#discountdetails');
   if (dde) dde.html('');
}

// executes a POST for the data contained in the master form to the specified URL
function postData(url, onsubmit) {   
   var theForm = document.forms['aspnetForm'];
   if (!theForm) {
       theForm = document.aspnetForm;
   }
   if (!onsubmit || (onsubmit() != false)) {
      theForm.action = url;
      theForm.method = 'POST';
      theForm.submit();
   }
}

// executes a GET for the data contained in the master form to the specified URL
function getData(url, onsubmit) {   
   var theForm = document.forms['aspnetForm'];
   if (!theForm) {
       theForm = document.aspnetForm;
   }
   if (!onsubmit || (onsubmit() != false)) {
      theForm.action = url;
      theForm.method = 'GET';
      theForm.submit();
   }
}

// executes a ajax POST for the data contained in the master form to the specified URL
function ajaxPostData(url, success, error, onsubmit) {
   var theForm = document.forms['aspnetForm'];
   if (!theForm) {
      theForm = document.aspnetForm;
   }
   if (!onsubmit || (onsubmit() != false)) {
      var params = $(theForm).serialize();
      $.ajax({
         url: url,         
         type: "POST",
         data: params,         
         success: success,
         error: error,
         async: false
      });
   }
}

// returns the position of the given element
// [not in use - may be removed]
function findPos(obj) 
{
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}

// loads the given article
function showArticle(articleNo) {
   document.location.href = 'main.aspx?page=article&artno=' + urlescape(articleNo);
}

// search for documents, input the search string
function searchDocuments(search) {
   document.location.href = 'main.aspx?page=documentlist&searchfld=documentsearch&searchstr=' + urlescape(search);
}

// search for articles, input the search string and search field
function searchArticles(search, field) {
   document.location.href = 'main.aspx?page=articlelist&requery=1&searchstr=' + urlescape(search) + '&searchfld=' + urlescape(field);
}

// search for either documents or articles 
function genericSearch() {
   var searchFieldSelect = document.getElementById('searchfld');
   var searchTextControl = document.getElementById('searchstr');
   
   if (searchTextControl && searchFieldSelect) {
      if (searchFieldSelect.value == 'documentsearch') {
         searchDocuments(searchTextControl.value);
      }
      else {
         searchArticles(searchTextControl.value, searchFieldSelect.value);
      }
   }
   return false;
}

// performs a request with the given sort order; sort direction is changed automatically
function orderBy(orderBy) {
   var href = document.location.href;
   var ascending = true;

   var orderIndex = href.indexOf('&order=');
   if (orderIndex != -1) {
      var orderIndexEnd = href.indexOf('&', orderIndex + 1);
      if (orderIndexEnd == -1) orderIndexEnd = href.length;      

      var order = href.slice(orderIndex + 7, orderIndexEnd);
      ascending = (order != 'desc');
      href = href.slice(0, orderIndex) + href.slice(orderIndexEnd);
   }

   var sortIndex = href.indexOf('&sort=');
   if (sortIndex != -1) {
      var sortIndexEnd = href.indexOf('&', sortIndex + 1);
      if (sortIndexEnd == -1) sortIndexEnd = href.length;

      var sortOrder = href.slice(sortIndex + 6, sortIndexEnd);
      if (decodeURIComponent(sortOrder) == orderBy) ascending = !ascending;
      href = href.slice(0, sortIndex) + href.slice(sortIndexEnd);
   }
   
   document.location.href = href + '&sort=' + encodeURIComponent(orderBy) + '&order=' + (ascending ? 'asc' : 'desc');
}

// adds one or more article to compare list (articleNo -> comma separated)
function addToCompare(sender, articleNo) {
   var elem = $(sender);

   if (elem.hasClass('added')) {
      if (elem.is('a')) return true; // once added follow href
      
      $.ajax({
         type: "POST",
         contentType: "application/json; charset=utf-8",
         data: "{ articleNumber: '" + articleNo + "' }",
         url: 'Pages/articlecompare.aspx/Remove',
         dataType: "json",
         success: function (result) {
            elem.removeClass('added').addClass('add').prop('checked', false);
         }
      });
   }
   else {
      $.ajax({
         type: "POST",
         contentType: "application/json; charset=utf-8",
         data: "{ articleNumber: '" + articleNo + "' }",
         url: 'Pages/articlecompare.aspx/Add',
         dataType: "json",
         success: function (result) {
            elem.removeClass('add').addClass('added').prop('checked', true);
         }
      });
   }

   return false;  // return false to cancel original behaviour
}

// when the document is ready (loaded)
$(document).ready(function() {
   // enable custom tooltips for article compare links
   $('a.comparebutton').tooltip({ effect: 'slide', position: 'bottom center', delay: 100 });
   $('input.comparebutton').tooltip({ effect: 'slide', position: 'left center', delay: 100, tipClass: 'tooltip-left', direction: 'right', offset: [110, -110] }); 
   
   // attach keypress event to all input controls
   $("input").bind("keypress", function(e) {
      var key = e.which || e.keyCode;
      if (key == 13) { // enter was pressed
         var li = document.getElementsByTagName("input");
         for (var i = 0, sl = false; i < li.length; i++) {
            if (!sl) {
               sl = (li[i] == this);
               continue;
            }
            if (li[i] && li[i].disabled == false && li[i].type != "hidden") {
               li[i].focus(); // move focus on this input
               if (li[i].type == "button" || li[i].type == "image" || li[i].type == "submit") {
                  li[i].click();  // perform a click on a clickable input
               }
               return false;
            }
         }
      }
   });
});
