/*
 * Remove buttons from dropdown forms
 * allow submit onchange for sort and items per page
 */
$(document).ready(function(){
    //add the por roll over info boxes:
//    var PORTEXT = "<div class=\"POR_Explain\">";
//    PORTEXT+="<h3>Price on request items:</h3>";
//    PORTEXT+="<p>Items that are marked 'price on request' can still be added to your cart, just like any other item.";
//    PORTEXT+="<br/>In order to recieve a quote of the items price, simply complete your order as normal.";
//    PORTEXT+="<br/>You will not be obliged to buy the items, rather you will simply have registered an interest.";
//    PORTEXT+="<br/>We will then contact you with the items price.";
//    PORTEXT+="<br/><b>Adding 'Price on request' items to any order does not incur any item, or delivery charges.</b></p>";
//
//
//
//    $(".PORBOX").html(PORTEXT).hide();
//    $(".PORBOX").parent().hover(
//        function(){
//            $(".PORBOX",this).fadeIn("fast");
//        },
//        function(){
//            $(".PORBOX",this).fadeOut("fast");
//        }
//    );
    //.sort and .perpage have dropdowns with go buttons
    //but with javascript we can submit the forms on select change and thus hide the unnessasary buttons to
    $(".sort .f_b,.perpage .f_b").hide();
//    $(".sort .f_g,.perpage .f_g").css('border','solid 1px #CCC');
//    $(".sort select,.perpage  select").css('padding-right',0);
    $(".sort select,.perpage select").change(function()
        {
        //submit the parent form ellement
        $(this).parents("form").submit();
        }
    );
});

/*
 * jquery powered slide show rotator
 */
var shownSlide = new Array();
var maxSlide = new Array();
var SlideShowRunning = new Array();
$(document).ready(function(){
   SlideBind();

});
function SlideBind(){
    $(".slideshow").each(
    function(){
        maxSlide.push($("div",this).length);
        SlideShowRunning.push(true);
        shownSlide.push(0);
        $(this).attr("id","SlideShow"+(maxSlide.length-1));
        SlideShowMovie(maxSlide.length-1);
    });

   $(".slidenav a").click(function(e){
          e.preventDefault();
           //need to trace to an array position id using DOM
           //we know it has one as we set it up in the first .each() function
          var ShowId  = parseInt($(".slideshow",$(this).parents(".slideshowwrapper")).attr("id").replace("SlideShow",""));
          if($(this).hasClass("pause")){
                $(this).toggleClass("active");
                SlideShowRunning[ShowId] = !SlideShowRunning[ShowId];
          }
          else{
          var imagetoshow = $(this).parent().attr("id").replace("slidenav","");
          RollSlideShow(imagetoshow,ShowId);
          }
   });
}
function SlideShowMovie(i){
    if(SlideShowRunning[i]){
        var Inshow = parseInt(shownSlide[i])+1;
        if(Inshow>maxSlide[i] || isNaN(Inshow)){Inshow=1;}
        RollSlideShow(Inshow,i);
    }
   setTimeout("SlideShowMovie("+i+")",5000);
}
function RollSlideShow(imagetoshow,i){
    var parent =  $("#SlideShow"+i).parents(".slideshowwrapper");
     if(shownSlide[i]!=0 && !isNaN(shownSlide[i])){
        if(shownSlide[i]!=imagetoshow){
        $("#SlideShow"+i+" div").fadeOut(1500);
        $("#SlideShow"+i+" div#slide"+imagetoshow).fadeIn(1500);

        shownSlide[i]=imagetoshow;
        $(".slidenav a:not(.pause)",parent).removeClass("active");
        $(".slidenav #slidenav"+imagetoshow+" a",parent).addClass("active");
        }
      }
      else{
          //0 is the start case
          //we simply move on the value and wait for a recall...
          shownSlide[i]=1;
          $(".slidenav a",parent).removeClass("active");
          $(".slidenav #slidenav"+1+" a",parent).addClass("active");
      }
}







/*
 * Code to launch the light box plugin
 */
$(document).ready(function(){
    $("a.lightBox").not(".ADMIN_pageeditorcanvas a.lightBox").lightBox({
	imageLoading:'/Theme/Default/Images/LightBox/lightbox-ico-loading.gif',
        imageBtnPrev:'/Theme/Default/Images/LightBox/lightbox-btn-prev.gif',
        imageBtnNext:'/Theme/Default/Images/LightBox/lightbox-btn-next.gif',
        imageBtnClose:'/Theme/Default/Images/LightBox/lightbox-btn-close.gif',
        imageBlank:'/Theme/Default/Images/LightBox/lightbox-blank.gif'
   }).click(function(){
        var Vheight = (window.innerHeight)-60;
        var Vwidth = (window.innerWidth)-60;
        var Vsize = Vheight;
        if(Vwidth<Vsize){Vsize = Vwidth;}
        $("#lightbox-container-image-box,#lightbox-nav a").css('max-height',Vsize).css('max-width',Vsize);
        $("#lightbox-container-image-box img,#lightbox-container-image-data-box").css('max-height',(Vsize-20)).css('max-width',(Vsize-20));
        $("#jquery-lightbox").css('top',20);
//   //if we want more control than that: I am better off writing my own plug in.//   //
    });
});

/*
 * copy info from billing to shipping address form
 */
$(document).ready(function(){
var BillToShip=$(".sameasbill").is(':checked');
$("input.billing").change(function(){

    if( BillToShip)
    {
     var ParentForm = $(this).parents("form");
     var name = $(this).attr("name").replace("billing","");
     $("input.shipping[name=shipping"+name+"]",ParentForm).val($(this).val());
    }
});


$(".sameasbill").change(function(){
   var ParentForm = $(this).parents("form");
   if($(this).is(':checked')){
        BillToShip=true;
       //ok so copy data and that//
      $("input.shipping",ParentForm).each(
        function(){
           var PageItem = ($(this).attr('name')).replace("shipping","");
           $(this).val($("input.billing[name=billing"+PageItem+"]",ParentForm).val()).attr('disabled', true).addClass("disabled");
        });
   }
   else{
        BillToShip=false;
       $("input.shipping",ParentForm).each(
        function(){
            $(this).removeAttr('disabled').removeClass("disabled");
        });
   }
});

});

/*
 * google map static to interactive
 */
$(document).ready(function(){

    if($(".map").length>0){
      //alert("NEW found "+$(".GOOGLEMAP").length+" maps...");
      var googlemapscript = document.createElement("script");
      //alert("Object created");
      googlemapscript.type = "text/javascript";
      //alert("typeSet");
      googlemapscript.src = "http://maps.google.com/maps/api/js?sensor=false&callback=LoadMaps";
      //alert("srcset");
      document.body.appendChild(googlemapscript);
     // alert("script added!");

    }
});


function LoadMaps() {
   // alert("initialize called");

    $(".map").each(

        function(){
            //alert("mapping a google map object");
            var alt = $("img", $(this)).attr("alt");
            var w = $("img", $(this)).width();
            var h = $("img", $(this)).height();


           $(this)[0].style.width=w+"px";
           $(this)[0].style.height=h+"px";
            var src_split = $("img", $(this)).attr("src").split("&");
            var LL = MapGetValue(src_split,"center");
            var myLatlng;
            var Markers=new Array();
            var myZoom = 15;
            if(LL!=null){
               LLSplit = LL.split(",");
               myLatlng = new google.maps.LatLng(LLSplit[0],LLSplit[1]);
               Markers[0]=LLSplit;
            }
            else{

               //here we want to go and get all marker co-ords..
               var markercount=0;
               var MarkersList = MapGetValue(src_split,"markers");
               //ok so look at splitting the above at %7C
               var MarkerListSplit = MarkersList.split("%7C");
               //now see if its a co-ordinate or not and add to the list if it is
              
               var l1 = 0;
               var l2 = 0;
               var maxLong = null;
               var maxLang = null;
               var minLong = null;
               var minLang = null;

               for(var thisval in MarkerListSplit)
               {
                   if(MapIsCoord(MarkerListSplit[thisval]))
                   {
                       Markers[markercount]=MarkerListSplit[thisval].split(",");
                       if(maxLong==null || maxLong<Markers[markercount][0]){maxLong = parseFloat(Markers[markercount][0]);}
                       if(minLong==null || minLong>Markers[markercount][0]){minLong = parseFloat(Markers[markercount][0]);}
                       if(maxLang==null || maxLang<Markers[markercount][1]){maxLang = parseFloat(Markers[markercount][1]);}
                       if(minLang==null || minLang>Markers[markercount][1]){minLang = parseFloat(Markers[markercount][1]);}

                       markercount++;
                   }

               }


              //ok center is maxlang-minlang
              if(markercount>1){
              var centerLong = (minLong + ((maxLong - minLong)/2));
              var centerLang = (minLang + ((maxLang - minLang)/2));
              myLatlng = new google.maps.LatLng(centerLong,centerLang);// +Math.abs((maxLong - minLong)/2),minLang +Math.abs((maxLang - minLang)/2));
              //optimal zoom //
              // Find the optimal Width and height Zoom
              var wZoom = 0;
              var wZ = ( maxLong - minLong );
                for (i = 1; i < 16; i++ ) {
                    if ( wZ > w ) break;
                    wZ *= 2;
                    wZoom = i;
                }
              var hZoom = 0;
              var hZ = ( maxLang - minLang );
                for (i = 1; i < 16; i++ ) {
                    if ( hZ > h ) break;
                    hZ *= 2;
                    hZoom = i;
                }
              //alert("wzoom is "+wZoom+" whilst hzoom is"+hZoom);
              //take the safest zoom and zoom out by 1 place..
              myZoom = (hZoom<wZoom?hZoom:wZoom);
              if(myZoom>1){myZoom--;}
             }
             else{
              myLatlng = new google.maps.LatLng(Markers[0][0],Markers[0][1]);
              myZoom = parseInt(MapGetValue(src_split,"zoom"));
            }


          }
           if(isNaN(myZoom)){myZoom=15;}

            var myOptions = {
                            zoom: myZoom ,
                            center: myLatlng,
                            mapTypeId: google.maps.MapTypeId.ROADMAP
                            };

            var map = new google.maps.Map($(this)[0], myOptions);
            for(var point in Markers){
                var localLongLat = new google.maps.LatLng(Markers[point][0],Markers[point][1]);
                var marker = new google.maps.Marker({
                        position: localLongLat,
                        map: map,
                        title:alt
                        });
            }
        }
    );

}
function MapGetValue(Array,Match){
    for(i=0;i<Array.length;i++){
             var thisval = Array[i].split("=");
             if(thisval[0]==Match){return thisval[1];}
    }
    return null;
}
function MapIsCoord(CoordStr){

    var splits = CoordStr.split(",");
    if(splits.length!=2){return false;}
    for(var val in splits){
        if(!MapIsNumeric(splits[val])){return false;}
    }
    return true;
}
function MapIsNumeric(sText)

{
   var ValidChars = "0123456789.-";
   var IsNumber=true;
   var Char;


   for (i = 0; i < sText.length && IsNumber == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsNumber = false;
         }
      }
   return IsNumber;

   }


/////  attribute minimising ////
$(document).ready(function(){
    //move the 2nd level feature attribute pairs to be hidden..
   var HideAttributeMenuDepth = 3;
    $(".prodmenu .full ul").not(".prodmenu .full:nth-child(-n+"+HideAttributeMenuDepth+") ul").each(function(){
        //only if its not in use...
        if(!$(this).has(".active").length ){
            $(this).hide();
            var wrapper = $(this).parents(".full");
            wrapper.addClass("minimisable")
            $("h3",wrapper).addClass("closed");
        }
    });


    $(".minimisable h3").click(function(e){
       e.preventDefault();
       var wrapper = $(this).parents(".full");
       $("ul",wrapper).slideToggle();
       $("h3",wrapper).toggleClass("closed").toggleClass("open");
    });
});

//date picker//
 //date picker
    $.datepicker.setDefaults($.datepicker.regional['']);
    $('.DatePicker').datepicker({ constrainInput: false , dateFormat: 'dd-mm-yy' });
