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);
		$("#"+link.id).html("My Favourite");
		$("#"+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();
		$("#add-favorite-"+alias).html("Add to Favourites");
		$("#add-favorite-"+alias).removeClass("is-favorite");
	}
	return false;
}

function removeAllFavorites(){
	if(confirm("Remove all favourites?")){
        	eraseCookie("fp_favorites");
		populateFavorites();
		$(".add-favorite").html("Add to Favourites");
		$(".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;
}

$('document').ready(function(){
        $('#main a[href^="http://"]').addClass('external').attr('target', '_blank');
        setTimeout("testFavCookie()",3000);
});


