/**
 *  Version 2.1
 *      -Contributors: "mindinquiring" : filter to exclude any stylesheet other than print.
 *  Tested ONLY in IE 8 and FF 3.6. No official support for other browsers, but will
 *      TRY to accomodate challenges in other browsers.
 *  Example:
 *      Print Button: <div id="print_button">Print</div>
 *      Print Area  : <div class="PrintArea"> ... html ... </div>
 *      Javascript  : <script>
 *                       $("div#print_button").click(function(){
 *                           $("div.PrintArea").printArea( [OPTIONS] );
 *                       });
 *                     </script>
 *  options are passed as json (json example: {mode: "popup", popClose: false})
 *
 *  {OPTIONS} | [type]    | (default), values      | Explanation
 *  --------- | --------- | ---------------------- | -----------
 *  @mode     | [string]  | ("iframe"),"popup"     | printable window is either iframe or browser popup
 *  @popHt    | [number]  | (500)                  | popup window height
 *  @popWd    | [number]  | (400)                  | popup window width
 *  @popX     | [number]  | (500)                  | popup window screen X position
 *  @popY     | [number]  | (500)                  | popup window screen Y position
 *  @popTitle | [string]  | ('')                   | popup window title element
 *  @popClose | [boolean] | (false),true           | popup window close after printing
 *  @strict   | [boolean] | (undefined),true,false | strict or loose(Transitional) html 4.01 document standard or undefined to not include at all (only for popup option)
 */
(function($) {
    var counter = 0;
    var modes = { iframe : "iframe", popup : "popup" };
    var defaults = { mode     : modes.iframe,
                     popHt    : 500,
                     popWd    : 400,
                     popX     : 200,
                     popY     : 200,
                     popTitle : '',
                     popClose : false };

    var settings = {};//global settings

    $.fn.printArea = function( options )
        {
            $.extend( settings, defaults, options );

            counter++;
            var idPrefix = "printArea_";
            $( "[id^=" + idPrefix + "]" ).remove();
            var ele = getFormData( $(this) );

            settings.id = idPrefix + counter;

            var writeDoc;
            var printWindow;

            switch ( settings.mode )
            {
                case modes.iframe :
                    var f = new Iframe();
                    writeDoc = f.doc;
                    printWindow = f.contentWindow || f;
                    break;
                case modes.popup :
                    printWindow = new Popup();
                    writeDoc = printWindow.doc;
            }

            writeDoc.open();
            writeDoc.write( docType() + "<html>" + getHead() + getBody(ele) + "</html>" );
            writeDoc.close();

            printWindow.focus();
            printWindow.print();

            if ( settings.mode == modes.popup && settings.popClose )
                printWindow.close();
        }

    function docType()
    {
        if ( settings.mode == modes.iframe || !settings.strict ) return "";

        var standard = settings.strict == false ? " Trasitional" : "";
        var dtd = settings.strict == false ? "loose" : "strict";

        return '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01' + standard + '//EN" "http://www.w3.org/TR/html4/' + dtd +  '.dtd">';
    }

    function getHead()
    {
        var head = "<head><title>" + settings.popTitle + "</title>";
        $(document).find("link")
            .filter(function(){
                    return $(this).attr("rel").toLowerCase() == "stylesheet";
                })
            .filter(function(){ // this filter contributed by "mindinquiring"
                    var media = $(this).attr("media");
                    return (media.toLowerCase() == "" || media.toLowerCase() == "print")
                })
            .each(function(){
                    head += '<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" >';
                });
        head += "</head>";
        return head;
    }

    function getBody( printElement )
    {
        return '<body><div class="' + $(printElement).attr("class") + '">' + $(printElement).html() + '</div></body>';
    }

    function getFormData( ele )
    {
        $("input,select,textarea", ele).each(function(){
            // In cases where radio, checkboxes and select elements are selected and deselected, and the print
            // button is pressed between select/deselect, the print screen shows incorrectly selected elements.
            // To ensure that the correct inputs are selected, when eventually printed, we must inspect each dom element
            var type = $(this).attr("type");
            if ( type == "radio" || type == "checkbox" )
            {
                if ( $(this).is(":not(:checked)") ) this.removeAttribute("checked");
                else this.setAttribute( "checked", true );
            }
            else if ( type == "text" )
                this.setAttribute( "value", $(this).val() );
            else if ( type == "select-multiple" || type == "select-one" )
                $(this).find( "option" ).each( function() {
                    if ( $(this).is(":not(:selected)") ) this.removeAttribute("selected");
                    else this.setAttribute( "selected", true );
                });
            else if ( type == "textarea" )
            {
                var v = $(this).attr( "value" );
                if ($.browser.mozilla)
                {
                    if (this.firstChild) this.firstChild.textContent = v;
                    else this.textContent = v;
                }
                else this.innerHTML = v;
            }
        });
        return ele;
    }

    function Iframe()
    {
        var frameId = settings.id;
        var iframeStyle = 'border:0;position:absolute;width:0px;height:0px;left:0px;top:0px;';
        var iframe;

        try
        {
            iframe = document.createElement('iframe');
            document.body.appendChild(iframe);
            $(iframe).attr({ style: iframeStyle, id: frameId, src: "" });
            iframe.doc = null;
            iframe.doc = iframe.contentDocument ? iframe.contentDocument : ( iframe.contentWindow ? iframe.contentWindow.document : iframe.document);
        }
        catch( e ) { throw e + ". iframes may not be supported in this browser."; }

        if ( iframe.doc == null ) throw "Cannot find document.";

        return iframe;
    }

    function Popup()
    {
        var windowAttr = "location=yes,statusbar=no,directories=no,menubar=no,titlebar=no,toolbar=no,dependent=no";
        windowAttr += ",width=" + settings.popWd + ",height=" + settings.popHt;
        windowAttr += ",resizable=yes,screenX=" + settings.popX + ",screenY=" + settings.popY + ",personalbar=no,scrollbars=no";

        var newWin = window.open( "", "_blank",  windowAttr );

        newWin.doc = newWin.document;

        return newWin;
    }
})(jQuery);


var timeout    = 500;
var closetimer = 0;
var ddmenuitem = 0;
var ddtopmenuitem = 0;
var openmenu = false;

function menu_open()
{
  menu_canceltimer();
  menu_close();

  if($(this).parent().find('ul').attr('id') != openmenu)
  {
    openmenu = $(this).parent().find('ul').attr('id');
    ddmenuitem = $(this).parent().find('ul').fadeTo('100', '0.99');
  }
  else
  {
    ddmenuitem = $(this).parent().find('ul').css('display', 'block');
  }

  ddtopmenuitem = $(this).addClass('navactive');
}

function menu_opened()
{
  menu_canceltimer();
  menu_close();

  ddmenuitem = $(this).css('display', 'block');
  ddtopmenuitem = $(this).parent().find('a:first').addClass('navactive');
}

function menu_close(resetmenu)
{
  $('#header-nav > li ul').hide();
  if(resetmenu == true)
  {
    openmenu = false;
  }

  if(ddtopmenuitem)
  {
    ddtopmenuitem.removeClass('navactive');
  }
}

function menu_timer()
{
  closetimer = window.setTimeout("menu_close(true)", timeout);
}

function menu_canceltimer()
{
  if(closetimer)
  {
    window.clearTimeout(closetimer);
    closetimer = null;
  }
}

var psTimeout = 10000;
var timer;

$(document).ready(function() {
  $('#header-nav > li > a').mouseover(menu_open);
  $('#header-nav > li ul').mouseover(menu_opened);
  $('#header-nav > li').mouseout(menu_timer);

  $('#page_limit').change(function() {
    window.location.href=$('#page_url').val()+'?limit='+$(this).val();
  });

  $('.lb').lightBox({
    'imageBtnPrev' : 'images/lightbox/lightbox-btn-prev.gif',
    'imageBtnNext' : 'images/lightbox/lightbox-btn-next.gif',
    'imageBtnClose' : 'images/lightbox/'+SEL_LANG+'/lightbox-btn-close.gif'
    });

  if($('#selector').length > 0) {
    productenSelector();
    timer = setTimeout("productenSelectorNext()", psTimeout);
  }

  $('a[rel=blank]').each(function() {
    $(this).attr('target', '_blank');
  });

  load_google_map();

  if(!Modernizr.input.placeholder) {
    $('input[placeholder]').each(function() {
      if($(this).val()=="" && $(this).attr("placeholder")!="")
      {
        $(this).css('color', '#CCC');
        $(this).val($(this).attr("placeholder"));
      }
    });

    $('input[placeholder]').live('focus', function() {
      if($(this).val()==$(this).attr("placeholder"))
      {
        $(this).val("");
        $(this).css('color', '#000');
      }
    });

    $('input[placeholder]').live('blur', function() {
      if($(this).val()=="")
      {
        $(this).css('color', '#CCC');
        $(this).val($(this).attr("placeholder"));
      }
    });

    if($('input[placeholder]').length > 0)
    {
      $('input[placeholder]:first').parents('form:first').submit(function(event) {
        event.preventDefault();
          $('input[placeholder]').each(function() {
            if($(this).val() == $(this).attr('placeholder'))
            {
              $(this).val('');
            }
          });

          $(this).unbind('submit');
          $(this).submit()
      });
    }
  }

   $('.scroll-pane-arrows').jScrollPane({ showArrows:true, verticalDragMinHeight: 10, verticalDragMaxHeight: 10 });


    $('.submenu li').click(function() {

    var the_href = $(this).find('a').attr('href');
    if(the_href.search('http://') >= 0)
    {
      document.location.href = the_href;
    }
    else
    {
      document.location.href = BASE_URL + the_href;
    }
  });

    $('.tooltip').tooltip({showURL: false});

   $("#print_button a").click(function(event){
     $(".jspContainer").printArea();
     event.preventDefault();
   });



});

$(document).unload(function() {
  GUnload();
});

function urlencode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'

    var histogram = {}, tmp_arr = [];
    var ret = str.toString();

    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };

    // The histogram is identical to the one in urldecode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';

    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);

    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }

    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });

    return ret;
}

function load_google_map()
{
  var markerHTML;

  markerHTML = $('#google_marker').html();

  var google_div = document.getElementById('google_map');

  if(google_div != null)
  {
    var myOptions = {
      zoom: 13,
      center: new google.maps.LatLng(latitude,longitude),
      navigationControl: true,
      disableDefaultUI: true,
      navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    var map = new google.maps.Map(document.getElementById("google_map"), myOptions);

    var myLatLng = new google.maps.LatLng(latitude, longitude);

    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map
    });

    var infowindow = new google.maps.InfoWindow({
      content: markerHTML
    });

    var newLatLng = new google.maps.LatLng(latitude-(-0.01),longitude);
    map.setCenter(newLatLng);

    infowindow.open(map,marker);
  }
}
