/**
 * Flash AJAX API implementation
 * 
 * Author: eihab@wallrichlandi.com
 * Copyright 2009, Wallrich Landi IMC
 */
var wallrichlandi = function(){};
wallrichlandi.wlapi = function(){};

wallrichlandi.wlapi.prototype.siteName   = 'Wallrich Landi'; // Site name (for <title>)
wallrichlandi.wlapi.prototype.currentURL = '/';              // Current URL (flash bookmarking)
wallrichlandi.wlapi.prototype.cache      = new Array();
wallrichlandi.wlapi.prototype.urlCache   = new Array();

/**
 * Get a cached page by ID (or URL)
 *
 * @param string ident   Resource identified (default: ID)
 * @param string type    Page type
 * @param bool   isURL   ident is a URL 
 */
wallrichlandi.wlapi.prototype.cacheGet = function(ident, isUrl) {
	if (isUrl) {
		var found = false;
		for (var i=0; i<this.urlCache.length; i++) {
			if (this.urlCache[i][0] == ident) {
				ident = this.urlCache[i][1]; 
				found = true;
				break;
			}
		}
		if (!found) return false;
	}
	for (var i=0; i<this.cache.length; i++) {
		if (this.cache[i][0] == ident) {
			return this.cache[i][1];
		}
	}
	return false;
}

/**
 * Store a page in cache
 *
 * @param string   url  Resource URL
 * @param Document doc  XML Document 
 */
wallrichlandi.wlapi.prototype.cacheStore = function(id, url, doc) {
	if(!this.cacheGet(id)) this.cache.push([id, doc]);
	for (var i=0; i<this.urlCache.length; i++) {
			if (this.urlCache[i][0] == url) {
				return;
			}
	}
	this.urlCache.push([url, id]);
}

// Last URL to check against in checkBrowserURL()
wallrichlandi.wlapi.prototype.lastURL = '/';
/**
 * Check page's URL and update flash as needed 
 * (Browser's back/forward "hack")
 */
wallrichlandi.wlapi.prototype.checkBrowserURL = function() {
	if (document.location.href != this.lastURL) {
		this.lastURL = document.location.href;
		if (document.location.href.indexOf('#')>-1) {
			url = document.location.href.split('#');
			w.currentURL = url[1];
		} else {
			var loc = document.location.href.split('/');
	
			if (loc.length > 3) {
				if (loc.slice(3).join('/').length > 0) {
					redirect = '/#/'+loc.slice(3).join('/');
				}
			}
		}
		w.initFlash(w.currentURL);
	}
}

// Variables for examples functionality 
wallrichlandi.wlapi.prototype.exID      = 0;
wallrichlandi.wlapi.prototype.exPageID  = 0;
wallrichlandi.wlapi.prototype.exGpid    = '';
wallrichlandi.wlapi.prototype.exGroupID = '';
/**
 * Show examples (Lightbox/prettyPhoto)
 *
 * @param int id     Portfolio/case ID to get
 * @param int pageID Current page ID
 * @param int type   Current page type
 */
wallrichlandi.wlapi.prototype.examples = function(id, pageID, type) {
	this.exGpid = new Array('wlv',
							id,
							'p',
							pageID).join('');
	this.exGroupID = new Array("a[rel^='prettyPhoto\[",
							this.exGpid,
							"\]']").join('');

	this.exID = id;
	this.exPageID = pageID;
	if ($(this.exGroupID).length < 1) {
		var self = this;
		$.ajax({
		   type: 'GET',
		    url: '/flashapi',
		   data: new Array('fullView=',id,'&type=',type).join(''),
	   dataType: 'xml',
		success: function(x) { 
				self.showLightBox(x);
			}
		});
	} else {
		this.showLightBox(false);
	}
}

/**
 * "Clean" up HTML for flash
 *
 * @param string str  HTML string to manipulate
 */
wallrichlandi.wlapi.prototype.formatHTML = function (str) {
	str = str.replace(/<\/(p|ul)>/gi,'</p><br/>');
	str = str.replace(/<strong>/gi,'<b>');
	str = str.replace(/<\/strong>/gi,'</b>');
	return str;
}

/**
 * Initiates AJAX call to retrieve page by id.
 * Hides current body.
 *
 * @param int id    Page ID to get
 */
wallrichlandi.wlapi.prototype.getPage = function (id, href) {
	if (href.indexOf('%u2019') > -1)
		href = href.replace('%u2019','%25E2%2580%2599');
	var cacheHit = this.cacheGet(id, 'p');
	this.currentURL = href;
	if (cacheHit) {
		this.parseResponse(cacheHit);
	} else {
		var self = this;
	
		$.ajax({
		   type: 'GET',
		    url: '/flashapi',
		   data: 'id='+id,
	   dataType: 'xml',
		success: function(x) { 
			self.parseResponse(x); 
			try { pageTracker._trackPageview(self.currentURL); } catch(e) { }
		},
		  error: function(x) {
		  	// Notify flash of error
		  	document.getElementById('flash'). pageLoadError(
		  		self.xmlToString(x));
		  }
		});
	}
}

/**
 * Initialize flash, get page and navigation
 *
 * @param string url    Initial page to load
 */
wallrichlandi.wlapi.prototype.initFlash = function(url) {
	if(!url) url = '/';
	var cacheHit = this.cacheGet(url, true);
	if (cacheHit) {
		this.currentURL = url;
		this.parseResponse(cacheHit, true);
		document.getElementById('flash') .initFlash(
			this.xmlToString(cacheHit));
	} else {
		var self = this;
		$.ajax({
		   type: 'GET',
		    url: '/flashapi',
		   data: 'url='+url,
	   dataType: 'xml',
		success: function(x) { 
		self.parseResponse(x, true);
		document.getElementById('flash') .initFlash(
			self.xmlToString(x));
			}
		});
	}
}

/**
 * Parse AJAX response and notify flash
 *
 * @param Document xml    Response
 * @param bool parseOnly  Do not notify flash, only modify title, etc.
 */
wallrichlandi.wlapi.prototype.parseResponse = function(x, parseOnly) {
	this.cacheStore($($('id', x)[0]).text(), this.currentURL, x);
	// Set document Title
	document.title = $($('title', x)[0]).text() + ' - ' + this.siteName;
	// Set document URL
	SWFAddress.setValue(this.currentURL);
	this.lastURL = document.location.href;
	if (!parseOnly)	// Notify flash
		document.getElementById('flash'). pageData(this.xmlToString(x));
}

/**
 * Resize flash container
 *
 * @param int h    New Height
 */
wallrichlandi.wlapi.prototype.resizeHeight = function(h) {
	$('#flash').height(h);
}

/**
 * Parse AJAX response and display lightbox
 */
wallrichlandi.wlapi.prototype.showLightBox = function(x) {
	if (x) {
		var mexGpid = this.exGpid;
		
		$('img', x).each(function(){
			if ($(this).text().indexOf('http') == 0) {
				window.open($(this).text());
				return;
			} else {
				var a = document.createElement('A');
				a.rel = new Array('prettyPhoto[',mexGpid,']').join('');
				a.href = $(this).text();
				a.className = 'mobile';
				$('body')[0].appendChild(a);
			}
		});
		$(this.exGroupID).prettyPhoto({
				showTitle:false,
				theme:'dark_rounded'
			});
	}
	$($(this.exGroupID)[0]).trigger('click');
}

/**
 * Convert XML Document to string
 *
 * @param Document xml    XML Document to convert
 */
wallrichlandi.wlapi.prototype.xmlToString = function (x) {
	try {
		return this.formatHTML((new XMLSerializer()).serializeToString(x));
	} catch (err) {
		try {
			return this.formatHTML(x.xml);
		} catch (err2) {
			alert("Your browser does not support XML functionality that's critical to view the flash version. \n\nYou will be re-directed to the non-flash site.");
			document.location.href = '/'+this.currentURL+'?nf=1';
		}
	}
}

// Back to top functionality
wallrichlandi.wlapi.prototype.backToTop = function() {
	window.scroll(0,0);
}

// Image box
// ['img1','img2','img3']
wallrichlandi.wlapi.prototype.imageBox = function(url) {
	if (typeof(url) == 'object') {
		var group = url.join('');
		if ($('a[rel=prettyPhoto['+group+']]').length == 0) {
			for (var i=0; i<url.length; i++) {
				var a = document.createElement('A');
				a.rel = new Array('prettyPhoto[',group,']').join('');
				a.href = url[i];
				a.className = 'mobile';
				$('body')[0].appendChild(a);
			}
		}
		$('a[rel=prettyPhoto['+group+']]').prettyPhoto({
				showTitle:false,
				theme:'dark_rounded'
			});		  

		$($('a[rel=prettyPhoto['+group+']]')[0]).trigger('click');
	} else {
		if ($('a[rel=prettyPhoto['+url+']]').length == 0) {
			var a = document.createElement('A');
			a.rel = new Array('prettyPhoto[',url,']').join('');
			a.href = url;
			a.className = 'mobile';
			$('body')[0].appendChild(a);
			$('a[rel=prettyPhoto['+url+']]').prettyPhoto({
					showTitle:false,
					theme:'dark_rounded'
				});
		}
		$('a[rel=prettyPhoto['+url+']]').trigger('click');
	}
}

var w; // Our API object
// Instantiate everything and get initial page
$(document).ready(function() {
	w = new wallrichlandi.wlapi;
	var url = '/';

	var redirect = false;
	
	if (document.location.href.indexOf('#')>-1) {
		url = document.location.href.split('#');
		w.currentURL = url[1];
	} else {
		var loc = document.location.href.split('/');

		if (loc.length > 3) {
			if (loc.slice(3).join('/').length > 0) {
				redirect = '/#/'+loc.slice(3).join('/');
			}
		}
	}

	var flashvars = {
		'redirect'   : redirect,
		'currentURL' : w.currentURL,
		'wWidth'     : $(window).width(),
		'wHeight'    : $(window).height()
	};
	
	var params = {
		'wmode' : 'transparent'
	};
	
	var attr = {
		'id' : 'flash'
	};
	
	swfobject.embedSWF("/wlFlash.swf", "flash", "100%", "600", 
					   "9.0.0", "expressInstall.swf", flashvars, params, attr);
	$('#flash').focus();
	w.lastURL = document.location.href;

	SWFAddress.onChange = function(e) {
		if (w.currentURL != SWFAddress.getValue()) {
			w.currentURL = SWFAddress.getValue();
			w.initFlash(SWFAddress.getValue());
		}
	};
});