String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }

var G_favStr = '';
var G_favCookie = '';

function compareAllFavorites() {
	if(G_favStr != null && G_favStr != ''){
		location = "/compare-ski-resorts.html?favres="+escape(G_favStr);
	}
}

function testFavCookie(){
	var cookieData = readCookie('fp_favorites');
	if(G_favCookie != cookieData){populateFavorites()}
	setTimeout('testFavCookie()',3000);

}

function populateFavorites (newFav) {
	var c;
	if (c = document.getElementById('favorites-list')) {
		c.innerHTML = '';
		var cookieData = readCookie('fp_favorites');
		G_favCookie = cookieData;
		if (cookieData == null || (typeof cookieData == 'string' && cookieData.trim()=='')){
 			c.innerHTML = '<p>You currently have no favourites saved.</p><p><img src=\"assets/templates/freshpeaks02/images/example-favourites.jpg\" width=\"429px\" height=\"158px\" alt=\"The Add to Favourites Link is situated in the top right hand corner of the site.\" /></p>';
			document.getElementById('favorites-options').style.display = 'none';
		} else {
			var favorites = cookieData.split(';');
			var html = '';
			var listN = 0;
			var favArr = new Array();
			for (var i=0; i<favorites.length; i++) {
				listN++;
				if(listN>6)listN=1;
				var x = favorites[i].split('~');
				var highlight = false;
				var fadefrom = new Array(255,255,51); // rgb colour
				if (newFav && newFav == x[1]) {
					highlight = true;
					for (var j=1; j<=10; j++) {
						setTimeout('if (cn = document.getElementById("myc'+i+'")) cn.style.backgroundColor="rgb('+Math.round(fadefrom[0]+(j/10)*(255-fadefrom[0]))+','+Math.round(fadefrom[1]+(j/10)*(255-fadefrom[1]))+','+Math.round(fadefrom[2]+(j/10)*(255-fadefrom[2]))+')";', ((j/10)*1000)+500);
					}
				}
				favArr.push(x[0]);
				if(listN == 1) html += '<td valign="top"><ul class="favorites-list">';

				//get the location - snowtown or resort
				// if it doesn't have the location, assume resort
				if (x.length <=2)
					loc = 'resort';
				else
					loc = x[2];

				html += '<li> <a href="javascript://" onClick="removeFavorite(\''+x[0]+'\')"><img src="/assets/templates/freshpeaks02/ui/side-bar-icon-x.png" border="0" title="Remove this favourite from your list" style="vertical-align:middle;"></a> <a onClick="unloadPage()" href="/'+loc+'_'+x[0]+'.html" id="myc'+i+'"'+(highlight?' style="background-color:rgb('+fadefrom[0]+','+fadefrom[1]+','+fadefrom[2]+');"':'')+'>'+x[1]+'</a></li>';
				if(listN == 6) html += '</ul></td>';
			}
			if(listN > 0 && listN < 6) html += '</ul></td>';
			G_favStr = favArr.join(',');
			document.getElementById('favorites-options').style.display = 'block';
			c.innerHTML = '<table border="0" cellpadding="0" cellspacing="0"><tr>'+html+'</tr></table>';
		}
	}
}

function favoriteExists (alias) {
	var favCookie = readCookie('fp_favorites');
	if (favCookie == null || favCookie == '') return false;
	var reg = new RegExp("\\b"+alias+"\\b");
	return reg.test(favCookie);
}

function addFavorite (link, alias, name, type) {
	name = name.trim();
	if (favoriteExists(alias)) {
		populateFavorites(alias);
		if (document.documentElement && document.documentElement.scrollTop)
			document.documentElement.scrollTop = 0;
		else if (document.body)
			document.body.scrollTop = 0;
		showFavorites();
		return false;
	}
	// If we have reached this point, we need to set the cookie
	var cookieData = readCookie('fp_favorites');
	createCookie("fp_favorites", (cookieData==null || cookieData.trim()=='' ? '' : cookieData+';')+alias+'~'+name+'~'+type, 30);

	if (!favoriteExists(alias)) {
		var cookieData = readCookie('fp_favorites');
		if (cookieData == null || cookieData == '') alert('Sorry, resort could not be added to favorites.\n\nPlease ensure that cookies are enabled in your web browser.');
		else alert('Sorry, this resort could not be added.\n\nYou may have too many items in favorites.');
	}else{
		populateFavorites(alias);
		jQuery("#"+link.id).html("My Favourite");
		jQuery("#"+link.id).addClass("is-favorite");
	}
	return false;
}

function removeFavorite (alias) {
	var cookieData = readCookie('fp_favorites');
	if (cookieData == null) {
		return false;
	}
	var removed = false;
	var favorites = cookieData.split(';');
	for (var i=0; i<favorites.length; i++) {
		if (alias.indexOf(favorites[i].split('~')[0]) != -1) {
			favorites.splice(i, 1); // remove this item from the array
			removed = true;
		}
	}
	cookieData = favorites.join(';');
	if (cookieData == '') cookieData = ' ';
	createCookie('fp_favorites', cookieData, 30);
	if (!removed) alert('Sorry, favorite could not be removed.');
	else{
		populateFavorites();
		jQuery("#add-favorite-"+alias).html("Add to Favourites");
		jQuery("#add-favorite-"+alias).removeClass("is-favorite");
	}
	return false;
}

function removeAllFavorites(){
	if(confirm("Remove all favourites?")){
        	eraseCookie("fp_favorites");
		populateFavorites();
		jQuery(".add-favorite").html("Add to Favourites");
		jQuery(".add-favorite").removeClass("is-favorite");
	}
}

function createCookie(name,value,days) {
        if (days) {
                var date = new Date();
                date.setTime(date.getTime()+(days*24*60*60*1000));
                var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+escape(value)+expires+"; path=/";
}

function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
        }
        return null;
}

function eraseCookie(name) {
        createCookie(name,"",-1);
}

function activateMovie(movieFile,container) {
	new Ajax.Updater(container, '/index.php?id=112&movieFile='+movieFile, {asynchronous:true, evalScripts:true});
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

jQuery('document').ready(function(){
        jQuery('#main a[href^="http://"]').addClass('external').attr('target', '_blank');
        setTimeout("testFavCookie()",3000);
        jQuery(".addthis_button_facebook_like iframe").css("width", "46px");
		
		pickOfTheWeekCheck();
    if (jQuery('#accommodation_partner_signup #country').length > 0) jQuery('#accommodation_partner_signup #country').customStyle();
    if (jQuery('#accommodation_partner_signup #property_type').length > 0) jQuery('#accommodation_partner_signup #property_type').customStyle();
    if (jQuery('#dining_partner_signup #country').length > 0) jQuery('#dining_partner_signup #country').customStyle();
    if (jQuery('#nightlife_partner_signup #country').length > 0) jQuery('#nightlife_partner_signup #country').customStyle();
    if (jQuery('#retail_partner_signup #country').length > 0) jQuery('#retail_partner_signup #country').customStyle();
    if (jQuery('#heli_partner_signup #country').length > 0) jQuery('#heli_partner_signup #country').customStyle();
    if (jQuery('#other_partner_signup #country').length > 0) jQuery('#other_partner_signup #country').customStyle();
    if (jQuery('#snow_town_signup #country').length > 0) jQuery('#snow_town_signup #country').customStyle();
    partnerForms();
    promotions();
    destinations();
});

function pickOfTheWeekCheck() {
	if(jQuery("#pickSelector") != undefined){	
		jQuery("#pickSelector").change(function() {
			jQuery.ajax({ url: "http://www.freshpeaks.com/5448",
						  data: "setId=" + this.options[this.selectedIndex].value});
		});
	}
}

function validateResortImage(){
  var honey=document.forms["resortImageUpload"]["honeyPot"].value;
  if (!(honey==null || honey==""))
  {
    alert("Form Validation Error, Please re-enter your details and try again.");
    return false;
  }

  var imageFile=document.forms["resortImageUpload"]["resortImage"].value;
  var trailMap=document.forms["resortImageUpload"]["trailMap"].value;
  var aerialShot=document.forms["resortImageUpload"]["aerialShot"].value;
  if ((imageFile==null || imageFile=="") && (trailMap==null || trailMap=="") &&(aerialShot==null || aerialShot==""))
  {
    alert("Form Validation Error, Please re-enter your details and try again.");
    return false;
  }
}

function destinations() {
  if (jQuery('.intro .btn-read-more').length <= 0) return;
  
  jQuery('.intro .btn-read-more').click(function() {
    element = jQuery('.intro .column-region-content')
    if (element.hasClass('collapsed')) {
      element.removeClass('collapsed');
      jQuery('.btn-read-more').css('background', 'url(\"assets/templates/freshpeaks02/images/icon_up.gif\") no-repeat 10px 13px #2696D6');
      jQuery('.btn-read-more').html('Read Less');
      jQuery('.intro .column-region-content').height('auto');
    }
    else {
      element.addClass('collapsed');
      jQuery('.btn-read-more').css('background', 'url(\"assets/templates/freshpeaks02/images/icon_down.gif\") no-repeat 10px 13px #2696D6');
      jQuery('.btn-read-more').html('Read More');
      
      var iCount = 0;
      jQuery('.intro .column-region-content p').each(function() {
        if (iCount == 2) {
          position = jQuery(this).offset().top;
          position -= jQuery(this).parent().offset().top;
          position += jQuery(this).height();
          jQuery('.intro .column-region-content.collapsed').height(position);
        }
        iCount++;
      });
    }
  });
  
  // When a link is clicked
  jQuery('h2 a').click(function () {
    classname='';
    classes = jQuery(this).parent().parent().parent().attr('class').split(' ');
    
    for (i=0 ; i < classes.length ; i++) {
      if (classes[i] != 'tabContent') classname=classes[i];
    }
    
    // switch all tabs off
    jQuery('.' + classname + ' .active').removeClass('active');
    // fadeout all elements with the class 'tabContent'
    jQuery('#' + classname + ' .tabContent').hide();
    // switch this tab on
    jQuery(this).parent().parent().addClass('active');
    // find 'title' attribute value is and find the element with that id. Then show it.
    var content_show = jQuery(this).attr('title');
    jQuery('#'+content_show).fadeIn();
    //don't go anywhere!
    return false;
  }); 
  
  jQuery('.intro .head .combo').click(function() {
    identification = jQuery(this).attr('id');
    identification = identification.split('-')[1];
    
    var self = this;
    
    jQuery('ul.region').each(function () {
      if (jQuery(this).attr('id').split('-')[1] != identification)
        jQuery(this).addClass('invisible');
    });
    jQuery('.intro .head .combo').each(function() {
      if (self != this)
        jQuery(this).removeClass('selected');
      else
        jQuery(this).removeClass('deactivated');
    });
  
    jQuery(this).toggleClass('selected');
    jQuery('#dropdown-' + identification).toggleClass('invisible');
    jQuery('.intro .head .combo').each(function() {
      if (this != self) 
        jQuery(this).toggleClass('deactivated');
    });
    return false;
  });
  
  jQuery(document).click(function() {
    jQuery('ul.region').addClass('invisible');
    jQuery('.intro .head .combo').removeClass('selected');
    jQuery('.intro .head .combo').removeClass('deactivated');
  });
  
  jQuery('ul.region li').mouseenter(function() {
    jQuery(this).parent().children('li').each(function() {
      jQuery(this).children('ul').addClass('invisible');
      //jQuery(this).parent().children('li').removeClass('border-right');      
      jQuery(this).removeClass('hover');
    });
    
    jQuery(this).addClass('hover');
    jQuery(this).children('ul').removeClass('invisible');
    if (jQuery(this).parent().hasClass('region'))
      jQuery(this).parent().children('li').addClass('border-right');
  });
  
  var iCount = 0;
  
  jQuery('.intro .column-region-content p').each(function() {
    if (iCount == 2) {
      position = jQuery(this).offset().top;
      position -= jQuery(this).parent().offset().top;
      position += jQuery(this).height();
      jQuery('.intro .column-region-content.collapsed').height(position);
    }
    iCount++;
  });
  
  toolTip();
}

function toolTip() {
  jQuery(".textToolTip").each(function(){
    var newTip;
    var elm = this;
    
    jQuery(elm).mouseenter(function(){
      var elmPosition = jQuery(elm).offset();
      var elmWidth = jQuery(elm).width();
      
      newTip = jQuery('<div></div>').attr('class', 'toolTipBox');
      newSpan = jQuery('<span>' + elm.title + '</span>');
      //jQuery(newSpan).innerHTML = elm.title;
      jQuery(newTip).prepend(newSpan);
      jQuery("#public").prepend(newTip);

      //var endLeft = elmWidth/2 + elmPosition.left - jQuery(newTip).width()/2;
      //var endTop = elmPosition.top - 28;
      var endLeft = elmPosition.left + jQuery(elm).width();
      var endTop = elmPosition.top + jQuery(elm).height() + 7;
      
      jQuery(newTip).css('left', endLeft + "px");
      jQuery(newTip).css('top', endTop + "px");
    });
    
    jQuery(elm).mouseleave(function(){
      jQuery(newTip).remove();
    });
  });
}

function partnerForms() {
  jQuery('#btn_showform').click(function() {
    jQuery('#signup_form').slideDown(200, function() {$.scrollTo(jQuery('#textpanel'), 800);});
    jQuery('.textpanel span').html('Please fill out the enquiry form below:');
    jQuery('.textpanel .btn_showform').addClass('invisible');
    
    return false;
  });
  
  jQuery('input:submit').click(function() {
    error = false;
  
    if (jQuery('.partner_signup form').attr('id') == 'prototype_partner_signup') {
      error = validate_Prototype();
    }
    if (jQuery('.partner_signup form').attr('id') == 'accommodation_partner_signup') {
      error = validate_Accommodation();
    }
    if (jQuery('.partner_signup form').attr('id') == 'dining_partner_signup') {
      error = validate_Dining();
    }
    if (jQuery('.partner_signup form').attr('id') == 'nightlife_partner_signup') {
      error = validate_Nightlife();
    }
    if (jQuery('.partner_signup form').attr('id') == 'retail_partner_signup') {
      error = validate_Retail();
    }
    if (jQuery('.partner_signup form').attr('id') == 'heli_partner_signup') {
      error = validate_Heli();
    }
    if (jQuery('.partner_signup form').attr('id') == 'other_partner_signup') {
      error = validate_Other();
    }
    if (jQuery('.partner_signup form').attr('id') == 'snow_resort_signup') {
      error = validate_Snowresort();
    }
    if (jQuery('.partner_signup form').attr('id') == 'snow_town_signup') {
      error = validate_Snowtown();
    }
    
    if (jQuery('.partner_signup form').attr('id') != 'snow_resort_signup') {
      if ($('#country').val().length <= 0) {
        jQuery('#country').parent().children('span').removeClass('invisible');
        error = true;
      }
      else {
        jQuery('#country').parent().children('span').addClass('invisible');
      }
    }
    
    if (jQuery('#name').val().length <= 0) {
      jQuery('#name').parent().children('span').removeClass('invisible');
      error = true;
    }
    else {
      jQuery('#name').parent().children('span').addClass('invisible');
    }
    
    if (jQuery('#email').val().length <= 0) {
      jQuery('#email').parent().children('span').removeClass('invisible');
      jQuery('#email').parent().children('span').text('You missed a field');
      error = true;
    }
    else {
      var x=jQuery('#email').val();
      var atpos=x.indexOf("@");
      var dotpos=x.lastIndexOf(".");
      if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
      {
        jQuery('#email').parent().children('span').removeClass('invisible');
        jQuery('#email').parent().children('span').text('Not a valid email address');
        error = true;
      }
      else
      {
        jQuery('#email').parent().children('span').addClass('invisible');
      }
    }
  
    if (error)
      return false;
    
    jQuery('#textpanel span').text('Sending enquiry...');
    jQuery('#signup_form').slideUp();
    
  
    
    return true;
  });

  jQuery('.form input').focus(function () {
    jQuery(this).parent().addClass('active');
  });

  jQuery('.form input').blur(function () {
    jQuery(this).parent().removeClass('active');
  });
  
  jQuery('.form input:checkbox').click(function () {
    jQuery(this).focus();
  });
  
  jQuery('.form select').focus(function () {
    jQuery(this).parent().addClass('active');
  });
  
  jQuery('.form select').blur(function () {
    jQuery(this).parent().removeClass('active');
  });
  
  jQuery('.btn_help').hover(helpOnMouseEnter, helpOnMouseLeave);
}

function validate_Prototype() {
  error = false;

  if (jQuery('#town_name').val().length <= 0) {
    jQuery('#town_name').parent().children('span').removeClass('invisible');
    error = true;
  }
  else {
    jQuery('#town_name').parent().children('span').addClass('invisible');
  }
  
  if (jQuery('#state').val().length <= 0) {
    jQuery('#state').parent().children('span').removeClass('invisible');
    error = true;
  }
  else {
    jQuery('#state').parent().children('span').addClass('invisible');
  }
  
  return error;
}

function validate_Accommodation() {
  error = false;

  if (jQuery('#property_name').val().length <= 0) {
    jQuery('#property_name').parent().children('span').removeClass('invisible');
    error = true;
  }
  else {
    jQuery('#property_name').parent().children('span').addClass('invisible');
  }
  
  if (jQuery('#property_type').val().length <= 0) {
    jQuery('#property_type').parent().children('span').removeClass('invisible');
    error = true;
  }
  else {
    jQuery('#property_type').parent().children('span').addClass('invisible');
  }
  
  if (jQuery('#property_location').val().length <= 0) {
    jQuery('#property_location').parent().children('span').removeClass('invisible');
    error = true;
  }
  else {
    jQuery('#property_location').parent().children('span').addClass('invisible');
  }
  
  return error;
}

function validate_Dining() {
  error = false;

  if (jQuery('#restaurant_name').val().length <= 0) {
    jQuery('#restaurant_name').parent().children('span').removeClass('invisible');
    error = true;
  }
  else {
    jQuery('#restaurant_name').parent().children('span').addClass('invisible');
  }
  
  if (jQuery('#restaurant_location').val().length <= 0) {
    jQuery('#restaurant_location').parent().children('span').removeClass('invisible');
    error = true;
  }
  else {
    jQuery('#restaurant_location').parent().children('span').addClass('invisible');
  }
  
  return error;
}

function validate_Nightlife() {
  error = false;

  if (jQuery('#venue_name').val().length <= 0) {
    jQuery('#venue_name').parent().children('span').removeClass('invisible');
    error = true;
  }
  else {
    jQuery('#venue_name').parent().children('span').addClass('invisible');
  }
  
  if (jQuery('#venue_location').val().length <= 0) {
    jQuery('#venue_location').parent().children('span').removeClass('invisible');
    error = true;
  }
  else {
    jQuery('#venue_location').parent().children('span').addClass('invisible');
  }
  
  return error;
}

function validate_Retail() {
  error = false;

  if (jQuery('#business_name').val().length <= 0) {
    jQuery('#business_name').parent().children('span').removeClass('invisible');
    error = true;
  }
  else {
    jQuery('#business_name').parent().children('span').addClass('invisible');
  }
  
  if (jQuery('#business_location').val().length <= 0) {
    jQuery('#business_location').parent().children('span').removeClass('invisible');
    error = true;
  }
  else {
    jQuery('#business_location').parent().children('span').addClass('invisible');
  }
  
  return error;
}

function validate_Heli() {
  error = false;

  if (jQuery('#company_name').val().length <= 0) {
    jQuery('#company_name').parent().children('span').removeClass('invisible');
    error = true;
  }
  else {
    jQuery('#company_name').parent().children('span').addClass('invisible');
  }
  
  if (jQuery('#operation_area').val().length <= 0) {
    jQuery('#operation_area').parent().children('span').removeClass('invisible');
    error = true;
  }
  else {
    jQuery('#operation_area').parent().children('span').addClass('invisible');
  }
  
  return error;
}

function validate_other() {
  error = false;

  /*if (jQuery('#restaurant_name').val().length <= 0) {
    jQuery('#restaurant_name').parent().children('span').removeClass('invisible');
    error = true;
  }
  else {
    jQuery('#restaurant_name').parent().children('span').addClass('invisible');
  }
  
  if (jQuery('#restaurant_location').val().length <= 0) {
    jQuery('#restaurant_location').parent().children('span').removeClass('invisible');
    error = true;
  }
  else {
    jQuery('#restaurant_location').parent().children('span').addClass('invisible');
  }*/
  
  return error;
}

function validate_Snowresort() {
    error = false;

  if (jQuery('#skiresort_name').val().length <= 0) {
    jQuery('#skiresort_name').parent().children('span').removeClass('invisible');
    error = true;
  }
  else {
    jQuery('#skiresort_name').parent().children('span').addClass('invisible');
  }
  
  return error;
}

function validate_Snowtown() {
    error = false;

  if (jQuery('#town_name').val().length <= 0) {
    jQuery('#town_name').parent().children('span').removeClass('invisible');
    error = true;
  }
  else {
    jQuery('#town_name').parent().children('span').addClass('invisible');
  }
  
  if (jQuery('#state').val().length <= 0) {
    jQuery('#state').parent().children('span').removeClass('invisible');
    error = true;
  }
  else {
    jQuery('#state').parent().children('span').addClass('invisible');
  }
  
  return error;
}

function helpOnMouseEnter() {
  id = jQuery(this).attr('id');
  id = id.substring(id.indexOf('-', 0) + 1, id.length);
  
  formfield_wrapper = jQuery(this).parent();
  form = formfield_wrapper.parent();
  formwrapper = form.parent();
  partner_signup = formwrapper.parent();
  
  padding_top = jQuery('#helptext-'+id).css('padding-top');
  padding_top = padding_top.substring(0, padding_top.indexOf('px'));
  padding_bottom = jQuery('#helptext-'+id).css('padding-bottom');
  padding_bottom = padding_bottom.substring(0, padding_bottom.indexOf('px'));
  padding_left = jQuery('#helptext-'+id).css('padding-left');
  padding_left = padding_left.substring(0, padding_left.indexOf('px'));
  padding_right = jQuery('#helptext-'+id).css('padding-right');
  padding_right = padding_right.substring(0, padding_right.indexOf('px'));
  
  position_top = jQuery(this).position().top;
  position_top += formfield_wrapper.position().top;
  position_top -= jQuery('#helptext-'+id).height();
  position_top -= padding_top;
  position_top -= padding_bottom;
  if (id == 0)
    position_top += 3;
  else
    position_top += 4;
  
  position_left = jQuery(this).position().left;
  position_left += formfield_wrapper.position().left;
  position_left -= jQuery('#helptext-'+id).width();
  position_left -= padding_left;
  position_left -= padding_right;
  position_left += 93;
  
  jQuery('#helptext-'+id).css({top: position_top + 'px', left: position_left + 'px'});
  jQuery('#helptext-'+id).removeClass('invisible');
}

function helpOnMouseLeave() {
  id = jQuery(this).attr('id');
  id = id.substring(id.indexOf('-', 0) + 1, id.length);
  
  jQuery('#helptext-'+id).addClass('invisible');
}

function promotions() {
  jQuery('.promotion-big .btn-close').click(function() {
    jQuery('.promotion-big').hide();
  });
}
