//trim function
String.prototype.trim = function () {
  return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

// ========================  COOKIES  =============================
function setCookie(cookieName,cookieValue,nDays) { 
  var today = new Date(); 
  var expire = new Date(); 
  expire.setTime(today.getTime() + 3600000*24*nDays); 
  document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString() + ";path=/"; 
} 

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1; 
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
return "";
}

function deleteCookie(cookieName) {
	setCookie(cookieName,0,-1);
}

//============================  HEADER ICON BUTTONS ====================================
function add_mouseover_to_buttons() {
  //mouseout for all buttons
    $("#header_buttons a").bind("mouseout", function() {
    	$("#hdr_button_desc").text("");
    }) 
    //mouseover buttons    
    .bind("mouseover", function() {
    	if (document.body.offsetWidth > 760) {
  		  $("#hdr_button_desc").text( $(this).attr("alt") ); 
		}
    });  

	//history and future
    $("#icon_backH, #icon_fwdH").bind("click", function(e) {
		e.preventDefault();
		//var url= $(this).attr("href");
		var $this_button = $(this);
		var this_action = $(this).attr("id").substring(5,99);  // find out which button was pressed from id eg "icon_backH" to "backH"
    	//alert(this_action);
		var url = $("#ajax").attr(this_action);  //find value in corresponding attribute in ajax div.
		if( url=="/"){
			window.location.href = url; //reload whole page if going to live
		} else {
			$("#refresh_area").load(url, function(){  //otherwise load in refresh area only via AJAX
				//check if body class needs to change (eg. from night to dusk) if so change it
				var new_bodyclass = $("#ajax").attr("bodyclass"); //look in ajax div for new value
				if ( !$("body").hasClass(new_bodyclass) ) {
					$("body").removeClass("day dusk night");
					$("body").addClass(new_bodyclass);
				}		
				 //site_remove_all_popups(); 
				 sites_animate_refresh(); //show sites that are on
				//setTimeout(function(){ $this_button.click(); },500); //just testing an auto forward
			});
		}
    })
    //help
    //$("#icon_help").bind("click", function(e) {
		//e.preventDefault();
		//alert(":hi");
    //})
       
}
// ========================= OPEN COMPACT  ===========================

function winOpenCompact() 
{ 
  var winName = 'compact' ;
  //if the current window name is compact then this must be an already opened and resized compact window so just resize it and change the location. 
  if(window.name==winName){
 	window.location.href="/windowResize.php";
  } else {//Otherwise open a new window.
    var left_pos = window.screen.availWidth - 160;
    var top_pos = 20;
    var wide=196;
    var high=116;
    destUrl="compact/";
    var windowprops = 'height=' + high + ',left=' + left_pos + ',top=' + top_pos + ',width=' + wide + ',directories=no,location=no,menubar=no,resizable=yes,scrollbars=no,status=no,titlebar=no,toolbar=no';
    window.open(destUrl, winName, windowprops); 
  }
}

//==================================  SITES DISPLAY  =====================================
//keep popups onscreen	
function site_ensure_onscreen($site_obj) {
    var site_height = $site_obj.outerHeight() -20;  //adjust for drop shadow borders
    var site_width = $site_obj.innerWidth() -20; 
    var site_position = $site_obj.position();    
    var site_top = site_position.top;        
    var site_left = site_position.left;  
	var window_height = $("#viewport").height(); 
	var window_width = $(window).width(); 
		
    //is site too high and overlapping the header?    
    var site_bottom = window_height - (site_top+site_height);
    if ( site_top < 50 ) { 
    	$site_obj.css({'top' : '50px'});    
    //is site too low and therefore off the bottom of the screen?
    } else if ( site_bottom < 15 ) { 
    	var new_site_top = site_top + site_bottom - 15; //yep so move it up
    	if (new_site_top < 0) { new_site_top=0 } //but make sure it's not off the top of the screen
    	$site_obj.css({'top' : new_site_top+'px'}); //move to new position
    }

    //is site too far right and therfore off the side of the screen?    
    var site_right = window_width - (site_left+site_width);
    if ( site_right < 5 ) { 
    	var new_site_left = site_left + site_right -15;  //yep so move it left (inc borders)
    	if (new_site_left < -5) { new_site_left=-5 }  //but make sure it's not off the left of the screen
    	$site_obj.css({'left' : new_site_left+'px'});  //move to new position
	// too left?
    } else if (site_left < -5) {
    	$site_obj.css({'left' : '-5px'});
    }

}

function site_remove_all_popups() {
  //get rid of any popups that may be open
  $(".object_site_popup").remove();
}

//get pop up via AJAX
function site_popup(site_code,e ) {
  site_remove_all_popups(); //get rid of any other popups that may be open
  //get popup info via ajax
  var url = "x_site_single_ajax.php?site_code="+site_code+"&wind_speed="+gv_wind_speed+"&wind_direction="+gv_wind_direction +"&tide_height="+gv_tide_height;
  $.ajax({
    url: url,
    cache: false,
    success: function(html){
      //data is now loaded so add to page
	  hide_site_throbber();
      $("body").append(html);
      $site_obj = $("#site" + site_code);
      //then fade in and move a bit 
      $site_obj.fadeIn("fast");  
      var offset = $(e.target).offset();
      $site_obj.css('left', offset.left-15).css('top', offset.top-50); 
      site_ensure_onscreen($site_obj);
    } //of success
  });
}

function show_site_throbber(e) {
  var offset = $(e.target).offset();
  $("#throbber").css('left', offset.left-15).css('top', offset.top-10).show();
	//$("#throbber").show();
}
function hide_site_throbber() {
	$("#throbber").hide();
}


var gv_site_timeout = false;
function add_mouseover_to_sites() {
  // popup on site mouseover
    $(".site_P, .site_P_off, .site_K, .site_K_off").live("mouseenter", function(e) {
		//if( $(event.target).hasClass('rating') ) return;
		//if($(this).hasClass("site_K")) $(this).stop().css('opacity',1);
	   	var site_code = $(this).attr('alt');  //get site code stored in attribute
	   	//create pop up after a short delay
		show_site_throbber(e);
		gv_site_timeout = setTimeout(function(){site_popup(site_code,e ); site_code=null; e=null;},150);
		
	//stop the above on mouseout to prevent quick pass overs from triggering
	}).bind("mouseout", function() {
    	clearTimeout(gv_site_timeout);  
  		hide_site_throbber();
	});   
	
      //popup to fade out then remove from page when mouse out or click
      $(".object_site_popup").live("mouseleave click", function() {
      //$(".object_site_popup").live("click", function() {
        $(this).fadeOut("fast", function() { 
          $(this).remove(); //when fade complete remove the popup from the DOM
        });
      }); //of bind	

}

  //alarm check 
//  if(gv_monkeyAlarm=="on") {
	 //check if there is a site that is on - site_display.php will have provided a div
//	 if( $("#best_site").length ) {
//	   var best_site_code = $("#best_site").attr("site_code");
//		$.ajax({
//		  url: 'wind_alarm.html',
//		  success: function(data) {
//		    $('body').append(data);
//		  }
//		});
		//show best site
//		$("div[alt='" +best_site_code+ "']").click();
//	 }
//  }


var gv_sites_animating = false;
var gv_sites_anim_timer;

function sites_animate(){
	if(!gv_sites_animating) { 
		//if there are any active sites then animate a pulsing effect on them
		if( $(".site_P, .site_K").length ) {
			//use flag to prevent mltiple firings
			gv_sites_animating = true;
			$(".site_P, .site_K").fadeOut("slow").fadeIn("fast",function(){
				gv_sites_animating = false;
				gv_sites_anim_timer = setTimeout('sites_animate()',1000);
			});

		}
	}
}

function sites_animate_refresh(){
	site_remove_all_popups();
	gv_sites_animating = false;
	clearTimeout(gv_sites_anim_timer); //stop any previous animation
	$(".site_P, .site_K").stop(true, true).css('opacity',1);  //clear any previous fading
	sites_animate();
}

//=================================== REFRESH =================================== 
function change_stylesheet(fromthis, tothis) {
  //change stylesheet - all in one now, just change body class
  //$("link[rel=stylesheet]").attr({href : "css_" +tothis+ "2.css"});
  $("body").removeClass('dusk night').addClass(tothis);

  //change all old images to the image named
  var outdated_image_search = "img[src*='" +fromthis+ "']";
  $(outdated_image_search).each( function(){
    cur_image = $(this).attr("src");
    new_image = cur_image.replace(fromthis,tothis);
    $(this).attr( {src : new_image } );
  });

  //special case for dusk arrow as it s/be day
  if (tothis=="dusk") {
	new_image = $("#arrow").attr("src").replace("dusk","day");
	$("#arrow").attr( {src : new_image } );
  }
  //special case for night arrow from day
  if (tothis=="night") {
	new_image = $("#arrow").attr("src").replace("day","night");
	$("#arrow").attr( {src : new_image } );
  }

  //if going from night add sites via ajax
  if (fromthis=="night") {
	//but only if they do not exist already
	if ( !$("#site_display").length ) {
	  url = "x_site_display.php?monkeyMode=" +gv_monkeyMode+ "&wind_speed_knots" +gv_wind_speed+ "&wind_direction_degrees=" +gv_wind_direction +"&tide_height="+gv_tide_height;
	  $("#site_display").load(url);
    }
  }

  gv_daynight = tothis;  //update global variable
}

function refresh_anounce() {
  //bounce right of wisemonkey lettering
  $("#head_back_left").animate({"left": "+=30px"}, 200, function(){
	  $("#head_back_left").animate({"left": "-=30px"}, 200);
  });
  //temp fade of viewport
  $("#viewport").fadeOut( 270, function(){
	  $("#viewport").fadeIn( 270);
  });	
}

function refresh_main_display(announce) {
  //default announce var to yes (it just gives a visual cue that refesh is happening)
  var announce = (announce == null) ? "yes" : announce;
  var url = "x_live_refresh.php";
  if (announce == "options") { url += "?options_refresh=true" }  //options changed so show day!!
		
  //get popup info via ajax
  $.ajax({
    url: url,
    cache: false,
    success: function(html){
      //data is now loaded so add to page
      $("#object_display").html(html);
      if (announce=="yes") {
        refresh_anounce();
      }
      //get wind data stored in alt's of divs
      gv_wind_speed = $("#ajax_wind_speed").attr('alt');
      gv_wind_direction = $("#ajax_wind_direction").attr('alt'); 
      gv_tide_height = $("#ajax_tide_height").attr('alt');
      //update monkey comments stored in alt's of spans   
      $("#hdr_monkey_comments").html( $("#ajax_monkey_comments").attr('alt') );
      //check if new data causes a change in daylight - if so change current css to match
      var new_daynight = $("#ajax_daynight").attr('alt');  
      if ( gv_daynight != new_daynight ) {
        change_stylesheet(gv_daynight, new_daynight);
      }
	  sites_animate_refresh(); //pulse any sites which are active
    } //of success
  }); //of ajax  	
}

function refresh_sites() {
  if(gv_wind_speed=="--") return;
  //clear all current sites and get newest via ajax - get wind speed etc from global variables
  $.ajax({
    url: "x_site_display.php?monkeyMode=" + gv_monkeyMode + "&wind_speed_knots=" +gv_wind_speed+ "&wind_direction_degrees=" + gv_wind_direction +"&tide_height="+gv_tide_height,
    cache: false,
    success: function(html){
      $("#site_display").html(html); //data is now loaded so add to page
	  sites_animate();
    }
  });	
}


function auto_refresh() {
  testsec = 60;
  refresh_main_display();
}

//count down
var testsec = 60;
function test_incsec() {
	testsec=testsec-1;
	$("#testId").text(testsec);	
}

//=================================== QUICK FORECASTS ===================================
function jsymetExpand() {
  //get rid of any site popups that may be open
  site_remove_all_popups();
  //..and hide options area if loaded and open
  if ($("#options_panel").length && parseInt($("#options_panel").css("left")) > -100 ) { 
	$("#options_close").click();
	}
  $("#options_open_link").hide();

  //if windguru not loaded - load it in.
  if( $("#windguru").text().length < 20) {
		$.ajax({
		  url: "windguru.php",
		  cache: false,
		  success: function(html){
		    $("#windguru").html(html);//data is now loaded so add to page
		  }
		}); 
   }

  //show, hide and animate 
  $("#object_swell").hide("slow"); 
  $("#qckfcst_clicktohide, #windguruOuter").show(); 
  $("#windguru").fadeIn("slow");
  $("#jsymet_outer").css("height", $("#jsymet_outer").height() + "px"); //try to fix IE glitch
  $("#jsymet_outer").slideToggle();
  $("#jsymet_opener").toggle();
}

function jsymetContract() {
  //..and show controls area
  $("#options_open_link").show();

  //reverse of jsymetExpand really
  $("#qckfcst_clicktohide").hide(); 
  $("#object_swell").show("slow");

  $("#windguru").fadeOut("slow", function(){
	$("#windguruOuter").hide(); 
  });

  $("#jsymet_outer").css("height", $("#jsymet_outer").height() + "px"); //try to fix IE glitch
  $("#jsymet_outer").slideToggle("slow", function(){ 
	$("#jsymet_opener").toggle();
	});

}

//=================================== OPTIONS AREAS ===================================
//global var for current option menu
var gv_cur_menu_id = "options_sites";

function options_initialise() {
	//show off-screen opener - if js is disabled options will not be accessible 
	$("#options_opener").animate({left:"-10px"},300);
	//add click event
	$("#options_opener").click( function(e){
		this.blur(); e.preventDefault();	
		site_remove_all_popups();
		//hide the opener
	 	$(this).animate({left:"-40px"},150, function(){
		    //if it's night the sites will be hidden within live - show them by doing a refresh from x_live_refresh
		    if(gv_daynight=="night") {
			  refresh_sites();
		    }
			//check if the panel has been already loaded. If so show it, otherwise load it via ajax and then show it
			if ($("#options_panel").length) {
				$("#options_panel").animate({left:"-2"},300);
			} else {
				$.ajax({
				  url: "x_live_options.php",
				  cache:false,
				  success: function(html){
				    $("body").append(html);
					$("#options_panel").animate({left:"-2"},300);
				  }
				}); //ajax
			} //options_panel length

	 	}); //animate
	 });
}

//====================================  OTHER ==========================================
function Xtest_new_data(speed,direction){
	gv_wind_speed=speed;
	gv_wind_direction=direction;
	url = "x_live_refresh.php?monkeyMode=" +gv_monkeyMode+ "&wind_speed_knots=" +gv_wind_speed+ "&wind_direction_degrees=" +gv_wind_direction;
	$("#object_display").load(url);
}

function initialise_live(){
  //add quickforecast events
  $("#jsymet_opener").click(jsymetExpand);
  $("#qckfcst_clicktohide").click(jsymetContract);
  //$("#wise_monkey_logo").click(winOpenCompact);

  //show items that are hidden when javascript is turned off
  options_initialise();

  //auto refresh of main display every 60 secs
  setInterval('auto_refresh()',60000);
  setInterval('test_incsec()',1000);	
}

function ipad_event(event){
	event.preventDefault() ;
}

//====================================  ON LOAD ==========================================
$(document).ready(function (){
  // add mouseover function to header buttons and all sites
  add_mouseover_to_buttons();
  add_mouseover_to_sites();  
  sites_animate(); //pulse any sites which are active
  $.ajaxSetup({ cache: false }); //turn AJAX cacheing off
});	


