/**
 * Javascript Common Library
 *  
 * LICENSE: This code is licenced to skinflips.com
 *
 * @package    DACH_SHOP
 * @subpackage PHP_WEBSITE 
 * @copyright  2010 Tortoise Design GmbH
 * @license    http://www.skinflips.com
 * @author     Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
 * @version    $Id: jsCommonLib.js 2328 2010-07-02 10:38:27Z nenadpet $
 * @link       http://www.skinflips.com
 * @since      File available since Release 0
*/


/**
 * Javascript Common Library Object
 *
 * This object contains common functions, used on most pages
 *  
 * Notice: prototype javascript framework needed
 *            
 * @package    DACH_SHOP
 * @subpackage PHP_WEBSITE 
 * @copyright  2010 Tortoise Design GmbH
 * @license    http://www.skinflips.com
 * @author     Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
 * @version    $Id: jsCommonLib.js 2328 2010-07-02 10:38:27Z nenadpet $
 * @link       http://www.skinflips.com
 * @since      File available since Release 0
*/
var jsCommonLib = {
  
  siteUrl:       null,  // site url
  siteStaticUrl: null,  // site static url
  siteMediaUrl:  null,  // site media url

  headerHeight: 90,           // current header height
  minViewPortHeight: 670,     // minimum view port height
  minMainContentHeight: 490,  // minimum main content container height

  //externalForms: ['trustedshopsCertificate'],  // forms that should be submited in new window

  /**
   * function: pageUnderConstruction
   * 
   * It throws alert (message)
   * 
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param  void
   * @return void
  */
  pageUnderConstruction: function() {
    alert('This part of website is under construction.');
  },

  /**
   * function: setMainContentContainerPusher
   * 
   * It sets main content container pusher height after user's current screen resolution
   * 
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param  void
   * @return void
  */
  setMainContentContainerPusher: function() {
    var browserViewPort = document.viewport.getDimensions();
    
    if (browserViewPort.height > jsCommonLib.minViewPortHeight) {
      var pusherHeight = ((browserViewPort.height - jsCommonLib.minMainContentHeight) / 2 ) - 15 - jsCommonLib.headerHeight;
      $('main-content-container-pusher').setStyle({'height': pusherHeight + 'px'});
    }
  },

  /**
   * function: getFormParams
   * 
   * It takes values for all form elements and makes post/get params variable used
   * for ajax request
   * 
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param  string $formId
   * @return string
  */
  getFormParams: function(formId) {
    var params = '?1=1';
    var elements = $(formId).elements;

    for (var i=0; i<elements.length; i++) {
      switch (elements[i].type) {
        case 'radio':
        case 'checkbox':
          if (elements[i].checked) {
            params += '&' + elements[i].name + '=' + elements[i].value;
          }
          break;

        case 'select-one':
          for (var k=0; k<elements[i].options.length; k++) {
            if (elements[i].options[k].selected) {
              params += '&' + elements[i].name + '=' + elements[i].options[k].value;
            }
          }
          break;

        case 'text':
        case 'textarea':
        case 'button':
        case 'hidden':
          params += '&' + elements[i].name + '=' + this.stringUrlEncode(elements[i].value);
          break;
      }
    }
    return params;
  },

  /**
   * function: stringUrlEncode 
   * 
   * URL encodes text string
   * 
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param  string $textString
   * @return string
  */
  stringUrlEncode: function(textString) {
    var tmp = '';
    textString = textString.toArray();

    for (var j=0; j<textString.length; j++) {
      if (textString[j] == "%") {
        tmp += escape(textString[j]);
      } else {
        tmp += textString[j];
      }
    }

    textString = tmp;

    var strForEncode = new Array("#","&","?");

    for (var i=0; i<strForEncode.length; i++) {
      while (textString.indexOf(strForEncode[i]) > -1) {
        textString = textString.replace(strForEncode[i],escape(strForEncode[i]));
      }
    }
    return textString;
  },

  /**
   * function: addLoadEvent
   * 
   * It adds function to BODY onload event
   * 
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param  object $func
   * @return null
  */
  addLoadEvent: function(func) {
    var oldOnload = window.onload;
    if (typeof window.onload != 'function') {
      window.onload = func;
    } else {
      window.onload = function() {
        if (oldOnload) {
          oldOnload();
        }
        func();
      };
    }
  },

  /**
   * function: inArray
   * 
   * Checks if given string is element of an array
   *
   * @author Sasa Simic <sasa.simic@softserbia.com>
   * @param  string  $check
   * @param  array   $arr
   * @return boolean
  */
  inArray: function(check, arr) {
    for(a in arr) {
      if (arr[a] == check) {
        return true;
      }
    }
    return false;
  },

  /**
   * function: externalLinks
   * 
   * Open rel="external" in new window - similar to target="_blank" in xhtml transitional
   *
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param  null
   * @return null
  */
  externalLinks: function() {
    if (!$$) return;  

    // <a> element
    var anchors = $$('a');
    for (var i=0; i<anchors.length; i++) {
      var anchor = anchors[i];
      if (anchor.getAttribute('href') && (anchor.getAttribute('rel') == 'external')) {
        anchor.target = '_blank';
      }
    }

    // <form> element
    /*
    var forms = $$('form');
    for (var i=0; i<forms.length; i++) {
      var form = forms[i];
      if (jsCommonLib.inArray(form['id'], jsCommonLib.externalForms)) {
        form.target = '_blank';  
      }
    }
    */

  },

  /**
   * function: Get cookie
   * 
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param  {String} cookieName  Cookie name
   * @return It returns cookie value
   * @type   String
  */
  getCookie: function(cookieName) {
    var cookieStart = null;
    var cookieEnd   = null;

    if (document.cookie.length > 0) {
      cookieStart = document.cookie.indexOf(cookieName + '=');
      if (cookieStart != -1) {
        cookieStart = cookieStart + cookieName.length + 1;
        cookieEnd = document.cookie.indexOf(';', cookieStart);
        if (cookieEnd == -1) {
          cookieEnd = document.cookie.length;
        }
        return unescape(document.cookie.substring(cookieStart, cookieEnd));
      }
    }
    return '';
  }, 

  /**
   * function: Set cookie
   * 
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param  {String} cookieName  Cookie name
   * @param  {String} cookieValue  Cookie value
   * @param  {Int} expireDays  Expire days
   * @return void
  */
  setCookie: function(cookieName, cookieValue, expireDays) {
    if (expireDays) {
      var date = new Date();
      date.setTime(date.getTime() + (expireDays * 24 * 60 * 60 * 1000));
      var expires = "; expires=" + date.toGMTString();
    } else {
      var expires = '';
    }

    document.cookie = cookieName + '=' + cookieValue + expires + '; path=/';
  }, 

  /**
   * function: Erase cookie
   * 
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param  {String} cookieName  Cookie name
   * @return void
  */
  eraseCookie: function(cookieName) {
    this.setCookie(cookieName, '', -1);
  }, 

  /**
   * function: image hover
   * 
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param {Int} getSwitch Hover type
   * @param {Object} getElement Element
   * @return It changes src of image element
   * @type null
  */
  imageHover: function(getSwitch, getElement) {
    var img = getElement.src;
    if (getSwitch == 2) {
        img = img.replace(/-over/gi, '-out');
    }
    else {
        img = img.replace(/-out/gi, '-over');
    }

    getElement.src = img;
  },

  /**
   * function: setCheckedRadioValue
   *
   * set the radio button with the given value as being checked
   * do nothing if there are no radio buttons
   * if the given value does not exist, all the radio buttons
   * are reset to unchecked
   *
   * @author Sasa Simic <sasa.simic@softserbia.com>
   * @param  {Object} radioObj radio object
   * @param  {String} newValue radio value to be checked
   * @return void
  */
  setCheckedRadioValue: function(radioObj, newValue) {
    if(!radioObj) return;
    var radioLength = radioObj.length;
    if(radioLength == undefined) {
      radioObj.checked = (radioObj.value == newValue.toString());
      return;
    }
    for(var i = 0; i < radioLength; i++) {
      radioObj[i].checked = false;
      if(radioObj[i].value == newValue.toString()) {
        radioObj[i].checked = true;
      }
    }
  },


  /**
   * function: Show fancy box
   * 
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param {String} ajaxUrl Url for ajax action
   * @return It returns false always
   * @type Boolean
  */   
  showFancybox: function(ajaxUrl) {
    var funcArgs = this.showFancybox.arguments;
    
    var data = null;
    if (typeof funcArgs[1] != 'undefined') {
      data = { aTagHref: funcArgs[1] };
    }

    // show fancybox
    var fancyBoxOptions = {
      'padding': 0,
      'margin': 0,
      'autoDimensions' : true,
      'transitionIn': 'swing',
      'transitionOut': 'swing',
      'speedIn' : 600, 
      'speedOut': 200, 
      'overlayShow': true,
      'hideOnContentClick': false,
      'showCloseButton': false
    };

    $j.fancybox.showActivity();

    $j.ajax({
      type: 'POST',
      cache: false,
      url: ajaxUrl,
      data: (data != null) ? data : $j(this).serializeArray(), 
      success: function(data) {
        $j.fancybox(data, fancyBoxOptions);
      }
    });
    
    return false;
  },


  /**
   * function: Close fancy box
   * 
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param void
   * @return void
  */   
  closeFancybox: function() {
    $j.fancybox.close();
    return false;
  },
  
  /**
   * function: This function is used for determine the laptop size of the display
   *           or choose a standard size.   
   * 
   * @author Ivana Djordjevic <ivana.djordjevic@softserbia.com>
   * @param  {Object} jsonResponse // json ajax response of addToShoppingBasket request
   * @return void  
  */  
  setCheckBoxes: function(cbIn, width, height) {
    if (cbIn == 'measured_own') {
      $('width').disabled = false;
      $('height').disabled = false;
      $('width').value = width;
      $('height').value = height;
    } else {
      $('width').disabled = true;
      $('height').disabled = true;
      switch (cbIn) {
        case 'measured_10':
          $('width').value = '240';
          $('height').value = '155';
          break;
        case 'measured_13':
          $('width').value = '310';
          $('height').value = '210';
          break;
        case 'measured_14':
          $('width').value = '315';
          $('height').value = '235';
          break;
        case 'measured_15':
          $('width').value = '320';
          $('height').value = '250';
          break;
        case 'measured_154':
          $('width').value = '350';
          $('height').value = '250';
          break;
        case 'measured_156':
          $('width').value = '360';
          $('height').value = '230';
          break;
        case 'measured_16':
          $('width').value = '365';
          $('height').value = '240';
          break;
        case 'measured_17':
          $('width').value = '390';
          $('height').value = '270';
          break;
      }
    }
  }


};

/**
 * function: string trim
 *
 * @author Sasa Simic <sasa.simic@softserbia.com>
 * @return void
*/
String.prototype.trim = function() {
  a = this.replace(/^\s+/, '');
  return a.replace(/\s+$/, '');
}
