
/**
 * Wishlist module.
 *
 * Wishlist is stored on client as cookie "wishlist". The cookie contents is an array
 * of wishlist records (id, name properties), encoded in JSON.
 */
 
var Wishlist = function(p_config) {
	
	var config = p_config;
	
	/**
	 * Add YP to wishlist. Update wishlist cookie (and server if SERVER_SIDE_WISHLIST set)
	 */
	function wishlistAdd (rec) {
		
		var wishlist = readWishlistFromCookie();
		
		// Check for duplicate and call onDuplicate method if set in config
		for (var i = 0; i < wishlist.length; i++) {
			if (wishlist[i].id == rec.id) {
				if (config.onDuplicate) {
					config.onDuplicate (wishlist[i]);
				}
				return;
			}
		}

		wishlist.push (rec);
		writeWishlistToCookie(wishlist);	
	}
	
	function wishlistRemove(id) {
		var wishlist = readWishlistFromCookie();
		var newWishlist = [];
		for (var i = 0; i < wishlist.length; i++) {
			if (wishlist[i].id != id) {
				newWishlist.push(wishlist[i]);
			}
		}
		writeWishlistToCookie(newWishlist);
	}
	
	/**
	 * Save wishlist to cookie
	 */
	function writeWishlistToCookie (wishlist) {
		var nc = YAHOO.lang.JSON.stringify(wishlist, ["id","name","image_id","loc","cl"] );
		//alert ('writeWishlistToCookie(): nc=' + nc);
		setCookie ("wishlist", nc ,null,"/");
	}
	
	/**
	 * Decode wishlist in cookie and return as array of wishlist records 
	 * with id,name properties
	 */
	function readWishlistFromCookie() {
		var wlc = getCookie("wishlist");
		//alert (wlc);
		if (wlc == "{}") {
			return [];
		}
		var wishlist = [];
		if (wlc != null) {
			//wishlist = eval( "(" + wlc + ")" );
			try {
				wishlist = YAHOO.lang.JSON.parse(wlc);
			} catch (e) {
				alert (e);
				return [];
			}
		}
		return wishlist;
	}
	

	//
	// Public methods
	//
	
	return {
		// Add item to wishlist
		add : function (ypId, ypName) {
			wishlistAdd(ypId,ypName);
		},
		// Remove item from wishlist
		remove: function (ypId) {
			wishlistRemove (ypId);
		},
		// Get array of wishlist objects (each id and name properties);
		list: function () {
			return readWishlistFromCookie();
		}
	}
	
};

// Create global wishlist object
// TODO: move this out of iasite.js
var wishlist = new Wishlist ({});

/**
 * Write comma separated list of wishlist ides to element
 */
function writeWishlistIds (elId) {
	var wl = wishlist.list();
	var html="";
	for (var i = 0; i < wl.length; i++) {
		html+= wl[i].id + ",";
	}
	var wlEl = document.getElementById(elId);
	YAHOO.util.Dom.setInnerHTML (wlEl,html);
}
		
function writeWishlistToForm (elId) {
		var wl = wishlist.list();
		
		var html="";
		for (var i = 0; i < wl.length; i++) {
			html+= wl[i].name + " (" + wl[i].id + ")\n";
		}
		var ffEl = document.getElementById(elId);
		YAHOO.util.Dom.setInnerHTML (ffEl,html);
}
	
/**
 * Write wishlist (as simle non-hyperlinked list) to element (used in
 * enquiry form)
 * @param elId
 */
function writeWishlist (elId) {
	var wl = wishlist.list();
	var html="<ul>";
	for (var i = 0; i < wl.length; i++) {
		html+="<li>" + wl[i].name + "</li>";
	}
	html += "</ul>";
	var wlEl = document.getElementById(elId);
	YAHOO.util.Dom.setInnerHTML (wlEl,html);
}
	
/**
 * Write wishlist into div #wish-list based on content of "wishlist" cookie
 */ 
function wishlistUpdate() {
	
	wl= wishlist.list();
		
	var html="<ul>";
	
	if (wl.length == 0) {
		//html += "<li>(there are no items in your wishlist)</li>";
		html += "<li>Browse Our Featured Listings</li>";
		html += "<li>Choose Where to stay, What to do</li>";
		html += "<li>Send us your request.</li>";
		html += "<li>We'll take care of the rest!</li>";
	}
	
	for (var i = 0; i < wl.length; i++) {
		var rec = wl[i];
		html+="<li id=\"wl_" + rec.id + "\"><a href=\"" 
		+ ROOT_LEVEL + "/all/yp-" + rec.id + ".html\">" 
		+ rec.name
		+ "</a> <a onclick=\"wishlist.remove(" + rec.id 
		+ ");wishlistUpdate();\" href=\"#\"><img src=\"" + ROOT_LEVEL + "/assets/del_16.gif\"/></a></li>";
	}
	html += "</ul>";
	
	var wlEl = document.getElementById("wish-list");
	YAHOO.util.Dom.setInnerHTML (wlEl,html);
}
	

/**
 * Shuffle array (for images)
 */
function shuffle(o){ 
	for(var j, x, i = o.length; i; j=parseInt(Math.random()*i), x=o[--i], o[i] = o[j], o[j] = x);
	return o;
};


function onRegionChange (el) {
	var newRegion = el.options[el.selectedIndex].value.toLowerCase();
	var categoryCode = document.getElementById("f_catCode").value;
	var subcatCode = document.getElementById("f_subcatCode").value;
	
	var url = ROOT_LEVEL + "/" + newRegion;
	// Choose appropriate url format:
	// either /(region)/(subcat)/index.html or /(region)/(category).html
	if (subcatCode.length > 0) {
		url+= "/"+subcatCode + "/index.html"
	} else if (categoryCode.length > 0) {
		url+= "/"+categoryCode + ".html";
	} else {
		url+= "/index.html";
	}
	window.location=url;
}


/**
 * Display mono slide show in 'fphoto' container
 */
function showSlideShow(ssfile) {
	var so = new SWFObject(ROOT_LEVEL+"/assets/monoslideshow.swf", 
		"SOmonoSlideshow", "450", "296", "7", "#628caf");
	so.addVariable("dataFile", ssfile);
	so.addVariable("showLogo", "false");
	so.addVariable("showVersionInfo", "false");
	so.write("fphoto");
}

function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} else
		begin += 2;
		var end = document.cookie.indexOf(";", begin);
		if (end == -1) end = dc.length;
	return unescape(dc.substring(begin + prefix.length, end));
}

function setCookie(name, value, expires, path, domain, secure) {
	var curCookie = name + "=" + escape(value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
 		((domain) ? "; domain=" + domain : "") +
 		((secure) ? "; secure" : "");
		document.cookie = curCookie;
}


/**
 * Code taken from ajaxian.com article to mitigate memory leak issues
 * with setInnerHTML
 *
 * http://ajaxian.com/archives/the-problem-with-innerhtml
 */
YAHOO.util.Dom.setInnerHTML = function (el, html) {
	el = YAHOO.util.Dom.get(el);
	if (!el || typeof html !== 'string') {
		return null;
	}

	// Break circular references.

	(function (o) {
		var a = o.attributes, i, l, n, c;
		
        if (a) {
			l = a.length;
			for (i = 0; i <l; i += 1) {
				n = a[i].name;
				if (typeof o[n] === 'function') {
					o[n] = null;
				}
			}
		}

		a = o.childNodes;
		if (a) {
			l = a.length;
			for (i = 0; i <l; i += 1) {
				c = o.childNodes[i];

				// Purge child nodes.
				arguments.callee(c);

				// Removes all listeners attached to the element via YUI's addListener.
				YAHOO.util.Event.purgeElement(c);
			}
		}
	})(el);

    // Remove scripts from HTML string, and set innerHTML property
    el.innerHTML = html.replace(/<script[^>]*>((.|[\r\n])*?)<\\?\/script>/ig, "");
    
    // Return a reference to the first child
    return el.firstChild;
};


	
