// MASTER JS
// SWFobject for IPS by sveinung@idium.no Feb 2010
(function f(b){var d=window.ips=window.ips||{},c=b||{loading:false},e;if(d.queue===undefined)d.queue=[];if(typeof window.swfobject!=="undefined"&&typeof window.swfobject.embedSWF!=="undefined")c.loading=false;else if(d.queue.length>0){if(c.loading===false){b=document.createElement("script");b.type="text/javascript";b.async=true;b.src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js";(document.getElementsByTagName("head")[0]||document.getElementsByTagName("body")[0]).appendChild(b); c.loading=true}e=setTimeout(function(){f(c)},50)}if(c.loading===false&&d.queue.length>0)for(b=0;b<d.queue.length;b++){var a=d.queue[b];if(!a.loaded){a.loaded="true";swfobject.embedSWF(a.url,a.element,a.width,a.height,a.version,a.expressInstall,a.flashvars,a.params,a.attributes)}}if(c.loading===false&&typeof window.jQuery!=="undefined")e=setTimeout(function(){jQuery(document).one("ajaxStart",function(){e=setTimeout(function(){f(c)},100)})},2E3)})();


//master.js
jQuery(document).ready(function($) {

 // DISPLAY USER INFO WHEN LOGGED IN
 $.ajax({
   url: ips.system.base + "?template=userLoggedIn&lang=" + ips.system.lang,
   cache: false,
   success: function(data) {
     jQuery(".nav_support li:last").before(data); // APPEND RESULT TO HEADER
   }
 });

  // Forgotten password
  $("#forgottenPassword").live("submit",function(e) {
    e.preventDefault();
    $("#forgottenPassword").find("strong").remove();
    $.get(
      base +
      "?module=Users&action=UserView.sendPassword&template=xml&email=" +
      $("input#email").val()
    ,
    function(data) {
      if($(data).find("EMAIL_PASSWORD[SUCCESS='true']").length) {
        $("#recoverPassword form").find("strong").remove();
        alert("En epost er sent til deg med et nytt passord.");
       $("#forgottenPassword").find("strong").remove();
      }
      else {
        $("#recoverPassword form").find("strong").remove();
        alert("Fant ingen bruker med denne e-postadresse");
        $("#forgottenPassword").find("strong").remove();
      }
    });
    $(this).append("<strong>Vennligst vent...</strong>");
  });

  $(".customSearch").keyup(function(e){
    e.preventDefault();
    if(e.which == '13') {
      var urlObj = {
        "module": "Search",
        "action": "Search.publicSearch",
        "qtype": "Articles.Article",
        "qroot": 54,
        "lang": ips.system.lang,
        "pagesize": "50",
        "template": "googlemap",
        "query": $(this).val()
      }
      $.ajax({
        url: ips.system.base + "?" + $.param(urlObj),
        success: function(data) {
          $(".map_wrapper").html(data);
          initializeMap();
        }
      }).ajaxStart(function() {
        $(".map_wrapper").addClass("loading");
      });
    }
  });

  $(".customSearch").focus(function(){ 
    $(this).attr("value", "");
  });

  $(".map_results a").live("click", function(e) {
    e.preventDefault();

    var urlObj = {
      "module": "Articles",
      "action": "Article.publicShow",
      "template": "googlemap",
      "id": $(this).attr("rel")
    }
    $.ajax({
       url: ips.system.base + "?" + $.param(urlObj),
      success: function(data) {
        $(".map_wrapper").html(data);
        initializeMap();
      }
    }).ajaxStart(function() {
      $(".map_wrapper").addClass("loading");
    });
  });

  $("a.dealer").live("click", function(e) {
    e.preventDefault();
    $(this).toggleClass("active");
    toggleVisibility(workshops);
  });
    
  $("a.workshop").live("click", function(e) {
    e.preventDefault();
    $(this).toggleClass("active");
    toggleVisibility(dealers);
  });

  // GOOGLE MAP
  var map;
  var marker;
  var dealers;
  var workshops;
  var bounds;      
  
  function initializeMap() {
    var latlng = new google.maps.LatLng(gm.counties.county.latlng.split(",")[0], gm.counties.county.latlng.split(",")[1]); // .trim()
    var myOptions = {
      zoom: 4,
      center: latlng,
      mapTypeControl: false,
      //maxZoom: 14,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("googlemap"), myOptions);
    bounds = new google.maps.LatLngBounds();
    initMarkers();

    if(dealers.length == 1 && workshops.length == 0) {
      map.setZoom(14);
      map.setCenter(dealers[0].getPosition());
    } else if(dealers.length == 0 && workshops.length == 1) {
      map.setZoom(14);
      map.setCenter(workshops[0].getPosition());
    } else if(dealers.length == 0 && workshops.length == 0) {
      map.setZoom(5);
      map.setCenter(latlng);
    } else {
      google.maps.event.addListener(map, 'zoom_changed', function() {
        zoomChangeBoundsListener =  google.maps.event.addListener(map, 'bounds_changed', function(event) {
          if (this.getZoom() > 15 && this.initialZoom == true) {
            // Change max/min zoom here
            this.setZoom(15);
            this.initialZoom = false;
          }
          google.maps.event.removeListener(zoomChangeBoundsListener);
        });
      });
      map.initialZoom = true;
      map.fitBounds(bounds);
    }
  }

  function initMarkers() {
      dealers = [];
      workshops = [];
      $.each(gm.counties.county.dealers, function (i, object) {
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(object.latlng.split(",")[0], object.latlng.split(",")[1]), //.trim()
        title: object.title,
        map: map
      });

  // Creating an InfowWindow
  var infowindow = new google.maps.InfoWindow({
      content: "<h3>"+ object.title + "</h3>" + "<br/>"+ "<p>" + object.text + "</p>"
  });
  // Adding a click event to the marker
  google.maps.event.addListener(marker, 'click', function () {
      // Opening the InfoWindow
      var pos = new google.maps.LatLng(object.latlng.split(",")[0], object.latlng.split(",")[1]); //.trim()
      infowindow.setPosition(pos);
      infowindow.open(map);
  });

      var point = new google.maps.LatLng(object.latlng.split(",")[0], object.latlng.split(",")[1]); //.trim()
      bounds.extend(point);
      if(object.type == 'Forhandler') {
        dealers.push(marker);
      }
      else if (object.type == 'Verksted'){
        workshops.push(marker);
      }
      else { // verksted AND forhandler
        dealers.push(marker);
        workshops.push(marker);
      }
    });

  }

  function toggleVisibility(markers) {
    for (var i = 0; i < markers.length; i++) {
      if (markers[i].getVisible()) {
        markers[i].setVisible(false);
      } else {
        markers[i].setVisible(true);
      }
    }
  }
  
  if( $(".map_wrapper").length) {
    $("select.counties").bind("change", function() {    
      var id;
      if ($(this).find("option:selected").val()) {
        id = $(this).find("option:selected").val();
      } else {
        id = 54;
      }
      $.ajax({
        url: ips.system.base + "?template=googlemap&id=" + id,
        success: function(data) {
          $(".map_wrapper").html(data);
          initializeMap();
        }
      })/*.ajaxStart(function() {
        $(".map_wrapper").addClass("loading");
      })*/;
    }).trigger("change");
  } 

  // END GOOGLE MAP

  $("a.fancybox").fancybox();

  $("a[rel=fancybox_group]").fancybox({
    'transitionIn'		: 'none',
    'transitionOut'		: 'none',
    'titlePosition' 	: 'over',
    'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
    return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
  }
  })

 /* used for cars, doesn't work with debug=true, really wierd bug */
  var menuHTML = '';
  var menuIndex = 0;
  jQuery(".product h5").each(function() {
    var menuItemText =  jQuery(this).text();
    menuHTML += '<li><a href="#';
    menuHTML += menuIndex;
    menuHTML += '">'
    menuHTML += menuItemText;
    menuHTML += '</a></li>';
    jQuery(this).hide().nextUntil("h5").hide();
    jQuery(this).addClass("index"+menuIndex);
    menuIndex++;
  });
  jQuery(".details_menu").append(menuHTML).find("a").unbind().bind("click",function(e){
    e.preventDefault();
    var index = jQuery(this).attr("href").substr($(this).attr("href").indexOf("#")+1);
    jQuery(this).parent().addClass("navigated");
    jQuery(".article .editorelement > *").hide();
    jQuery(".summary_expanded > *").hide();
    jQuery(".files > *").hide();
    jQuery(".gallery > *").hide();
    jQuery(".gallery > *").show();
    jQuery(".editorelement").css('display', 'block');
    var $h5 = jQuery(".product").find(".index"+index);
     $h5.show();
     $h5.nextUntil("h5").show();
  });

  
 

  // ARTICLE CARUSEL
  var $carusel = $('div.article-carusel');
  if ($carusel.size()) {
    $carusel.after('<div class="carusel_menu"><div class="nav_carusel"></div></div>').cycle({
        speed:  'slow',
        timeout: 6000,
        pager:  '.nav_carusel',
        pause:   1
    });
   }
   
   $("h2.hyretop").css('marginLeft', '500px');
   $("h2.midttopp").css('marginLeft', '300px');
   $("h2.venstreu").css('marginTop', '200px');
   $("h2.midtunde").css('marginTop', '200px').css('marginLeft', '300px');
   $("h2.hyreund").css('marginTop', '200px').css('marginLeft', '500px'); 

   $('.fronpage_content_under li').each(function(index) {
     $(this).addClass('item'+index);
   });

   $('body').ajaxSuccess(function() {
     var resultsvalue = $('h3.resultheader').text();
     var valueboolean = Boolean(resultsvalue);
     if(valueboolean == true) {
       $('.templatelabel_dealers  .content_container').addClass('shaddowbottom');
     }
   });

   // UTILITY
   var base = ips.system.base; //cache as local variable

   // Searchform interaction
   var $searchForm = $("#search_form"), //CACHE
       $query = $searchForm.find(".query"),
       $label = $searchForm.find("label");
   if ($query.val() !== "") {$label.hide();}
   $searchForm.submit(function(){
   if ($query.val() === "") {return false;}
   });
   $query.focus(function(){$label.hide();}).blur(function(){
     if ($(this).val() === "") {$label.show();}
   });
   $searchForm.find("label").click(function(){
    $query.focus();
   }); 
  // EVENT DELEGATION - Not touching dom until click
  $(".externalLink").live("click", function(){
    $(this).attr("target", "_blank");
  });


  // IPS FORM validation by sveinung@idium.no March 2010
  $("body").delegate("form", "submit", function(e){
    var $this = $(this), formid = $this.attr("id")+"", errors = [];
    // Start validation object
    //fix broken objects
    var ips = window.ips = window.ips ||{};
    ips.validate = ips.validate ||{};
    ips.validate[formid] = ips.validate[formid] ||{};
    //end fix broken objects

  // Reset, and FIND/QUERY viable <li> tags. Must be typical <li> with input. If different, change next find().
    $this.find("span.error").remove().end().find("li:not(.submit,.form_labelfield)").removeClass("error")
    // START each - > iterate li`s
    .each(function(i){
    // Needed vars and Cache selectors for convenience and "speed"
      var $li = $(this), $nextLi = $li.next(), $prevLi = $li.prev(), $field = $li.find("input,textarea,select").eq(0), fid = $field.attr("id"), fieldval = $field.val(), errorObj = {"id":fid,"$elem":$li,"message":""};
      // Utilty function for checking regex values
      var checkFunc = function(regexObj, thisval, message, errorObj){
      if (!regexObj.test(thisval)) {
        errorObj.message = message;
      } else {
        errorObj.valid = true; // used to make this rule more important than classes
      }
      return errorObj;  
      };
      // Iterating and validation all regexes in the general object
      $.each(ips.validate.general, function(property){
      if ($li.hasClass(property) && this.regex !== undefined ) {
        errorObj = checkFunc(this.regex, fieldval, this.message, errorObj);
      }
      });
      // Check for validation object
    if ( ips.validate[formid][fid] !== undefined && ips.validate[formid][fid].regex !== undefined ) {
     var fieldvalObj = ips.validate[formid][fid],
           errorMgs = fieldvalObj.message !== undefined ?  fieldvalObj.message : ips.strings.notvalid;
       errorObj = checkFunc(new RegExp(fieldvalObj.regex), fieldval, errorMgs, errorObj);
      } else {
      //fix missing objects
      ips.validate[formid][fid] = {};
      }
      if ( $li.hasClass("form_password") && errorObj.message === ''){
        errorObj = checkFunc(ips.validate.general.password.regex, fieldval, ips.validate.general.password.message, errorObj);
        if (errorObj.message === "" && fieldval !== $li.find(".confirm").val()) {
        errorObj.id = $li.find(".confirm").attr("id");
        errorObj.message = ips.validate.general.password.message;
        }
      }
      // Check username if form has class .loggedout -> Forms get resubmitted if error from server
      if ( $this.hasClass("loggedout") && $li.hasClass("username") && !(errorObj.valid)){
        var searchedUsername = $.data($field[0],"username"), // get "cacge"
            availFromPrevSubmit = $.data($field[0],"avail"); // get "cache"
        $.data($field[0],"username",fieldval); // write "cache"
        // Check if new desired username isnt equal to previous ones or if no username has been checked
        if ((fieldval !== searchedUsername) || (availFromPrevSubmit === null) ) { 
        // Async - check param, then set value on elem and resubmit form
        $.get(ips.system.base + "?module=Users&amp;action=Ajax.isUsernameAvailable&amp;username="+fieldval, function(data){
         $.data($field[0],"avail",data);
         // 'false' is serverresponse in plain text
         if (data == 'false') {
           setTimeout(function(){$this.submit();},100);
         }
        });
        } else {
        // check if this is checked and username is not avail === false
        if (availFromPrevSubmit == "false") {
          errorObj.message = ips.strings.usernamenotavail;  
        }  
        }
      }
      	// Check custom class, and recheck _class
      var testCustom = /required_if_not_([a-zA-Z0-9]+)/.exec($li.attr("class"));
      if (testCustom && testCustom[1] && testCustom[1] !== '') {
          if ($("." + testCustom[1]).find("input,textarea,select").eq(0).val() == '') {
              // if other field has no value, this field is required
              $li.addClass("required");
          } else {
              // if other field has value, this field isnt required
              $li.removeClass("required");
          }
          // check if .required and 
      } else if (fieldval === '' &&  $li.hasClass("required")) {
        // If not already a error - add a error message
      if (errorObj.message === '') {
          errorObj.message = ips.strings.cannotbeempty;
     }
      } else if ($li.hasClass("required") && errorObj.message === '') {
        // if checkbox is required
        if ($field.is("input[type=checkbox]") && $field.attr("checked") === false) {
          errorObj.message = ips.validate[formid][fid].message ||ips.strings.mustbechecked;
        }
      }
      // Todo, ADD : requiredIf - (e.g. email, checkbox )
      // Check for customclasses 'isequaltonext' and 'isequaltoprev' - > is in lowercase bacause of ips:classify
    if ($li.hasClass('isequaltonext')||$nextLi.hasClass('isequaltoprev')) {
        if (fieldval !== $nextLi.find("input").val()) {
        errorObj.message = $li.find("label").text() + ips.strings.mustbeequalto + $nextLi.find("label").text();
        }
      }  else if ($li.hasClass('isequaltoprev')||$prevLi.hasClass('isequaltonext')) {
        if (fieldval !== $prevLi.find("input").val()) {
        errorObj.message = $li.find("label").text() +  ips.strings.mustbeequalto + $prevLi.find("label").text();
        }
      }
      // Field is not required, NO error-msg should be generated
      if (fieldval === '' && !($li.hasClass("required"))) {
      errorObj.message = ''; 
      }
      // Push this errorObj if there is a message defined
      if ( errorObj.message !== undefined && errorObj.message !== '' ) {
      errors.push(errorObj);
      }
    }); //END each li`s

    if ( ips.system.parameters.debug ) {
      console.log(errors);
    }  // Process errors if there is any
    if ( errors.length > 0 ) {
      $( errors ).each(function(i){
        var $errorField = this.$elem.addClass("error").find("input,textarea,select").eq(0);
        if (i === 0) {$errorField.focus();}
        $("<span class='error'>" + this.message + "</span>").insertAfter( $errorField );  
      });
      return false;
    }
  });
  // Possible to click the errors away
  $("span.error").live("click", function(){$(this).fadeOut();}); 
  //FORM END
  if($("#galleria").length > 0) {
    // Load the classic theme
	  Galleria.loadTheme(ips.system.base+'filestore/dev/JS/galleria.classic.min.js');
	  // Initialize Galleria
	  $('#galleria').galleria();
  }
}); // #### end of document ready ####
