// 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($) {

   // UTILITY
   var base = ips.system.base; //cache as local variable

   // Searchform interaction
   var $search_form = $("#search_form"), //CACHE
       $query = $search_form.find(".query"),
       $label = $search_form.find("label");
   if ($query.val() !== "") {$label.hide();}
   $search_form.submit(function(){
   if ($query.val() === "") {return false;}
   });
   $query.focus(function(){$label.hide();}).blur(function(){
     if ($(this).val() === "") {$label.show();}
   });
   $search_form.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 if .required and 
      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;
    // default action of the event will not be triggered.
    //e.preventDefault();
    // Keeps the rest of the handlers from being executed.
      //e.stopImmediatePropagation();
    }
  });
  // Possible to click the errors away
  $("span.error").live("click", function(){$(this).fadeOut();}); 
//FORM END
});

$(window).load(function(){
  	var $gmaps = $("a[href*=http://maps.google] img");
	if ($gmaps.size()) {
	  // miniplugin
	  jQuery.fn.makeObj = function() {
		    href = this.eq(0).attr("href");
		    var splitted = href.substring( href.indexOf("?")+1 ).split("&"), obj = {}; 
		    // iteratte and make a workable obj
		    for ( var i = 0; i < splitted.length; i++ ) {
		      var ins = splitted[i].split("=");
		      if (ins[1] !== undefined && ins[1] !== "") obj[ ins[0] ] = ins[1];
		    }
		    return obj;		 
	  };
	  //Iterate imgs
	  $gmaps.each(function(i){
	    var $t = $(this), $p = $t.parent(), 
	        obj = $p.makeObj(),
	        width  = $t.width()*1 > 10 ? $t.width() : 200,
	        height = $t.height()*1 > 10 ? $t.height() : 300,
	        elem   = "<div class='gmap' style='position:relative;width:"+width+"px; height:"+height+"px'>";
	        elem  += "<div class='gmap"+i+"' style='width:100%;height:100%;'></div>";
	        elem  += "<a class='gmaplink"+i+"' target='_blank' style='display:none;position:absolute;";
	        elem  += "top:2px;right:2px;z-index:1000' href='"+$p.attr("href")+"'>Se fullt kart</a></div>";
	        var view = obj.ll ? obj.ll.split(",") : obj.sll.split(","),
	        setupObj = {
	          "zoom" : obj.z *1,
	          "center": new google.maps.LatLng( view[0]*1, view[1]*1 ),
	          "mapTypeId" : google.maps.MapTypeId.ROADMAP,
	          "disableDefaultUI" : false
	        };
	    $p.replaceWith(elem);
	    var gmapref = new google.maps.Map($(".gmap"+i).get()[0], setupObj),
	        point = obj.ll ? obj.ll.split(",") : obj.sll.split(","),
	        marker = new google.maps.Marker({
		        position: new google.maps.LatLng( point[0]*1, point[1]*1 ), 
		        map: gmapref,
		        title: obj.q||obj.hnear||''
		    });
	    $(".gmap").hover(function(){$(this).find(".gmaplink"+i).toggle();});
	  });
	}
});

function facebook_click() {
  u=location.href;
  t=document.title;
  window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
  return false;
}
