var SlidePage = Class.extend({
	init: function(options, elem){
		this.$elem = $(elem);
		this.options.targetID = this.$elem[0].id;
		this.options.transitionID = this.options.targetID;
		this.options = $.extend({}, this.options, options);
		return this;
	},
	options: {
		targetID: null,
		transitionID: null,
		transitionGraphicID: 'SlidePageLoadingDefault',
		fadeOutTimeout: 400,
		fadeInTimeout: 600,
		ajaxTimeout: 0,
		bindingClass: 'js-slide',
		historyData: 'pushed',
		protocol: window.location.protocol,
		loadingGraphicPath: '//images.ifriends.net/if_v2/loading.gif',
		loadedScripts: []
	},
	build: function() {
		this._bindLinks();
		this._bindPopState();
		this._prepareHistory();
		this._bindUnload();
	},
	handleAjaxSuccess: function(url, data) {
		//pass
	},
	handleAjaxFailure: function(url) {
		window.location.href = url;
	},
	onClickDoFirst: function(targetURL, currentURL) {
		return targetURL;
	},
	_loadPage: function(url) {
			var targetURL = url;
			this._showLoading();
			this._unbindLinks();
			this._bindEscIntercept();
			jQuery.ajax({
				url: url + "&pLinkType=partial",
				cache: false,
				context: this,
				timeout: this.options.ajaxTimeout,
				dataType: 'html',
				success: function(data) {
					if (data.search('DOCTYPE') !== -1) {
						this.handleAjaxFailure(targetURL);
					} else {
						var customResponseData = this._handleResponseScripts(data),
							targetDIV = this.options.targetID,
							sliderObj = this;
						if (customResponseData.scripts.length) {
							for (var iter = 0; iter < customResponseData.scriptsToPreload; iter++) {
								jQuery.ajax({
									url: customResponseData.scripts[iter].src,
									dataType: 'script',
									success: function() {
										customResponseData.scriptsLoaded++;
										if (customResponseData.scriptsToPreload == customResponseData.scriptsLoaded) {
											jQuery('#' + targetDIV).html(customResponseData.data);
											sliderObj._afterDOMInsert(targetURL, data);
										}
									},
									error: function() {
										sliderObj.handleAjaxFailure(targetURL);
									}
								})
							}
						} else {
							jQuery('#' + targetDIV).html(customResponseData.data);
							this._afterDOMInsert(targetURL, data);
						}
					}
				},
				error: function() {
					this.handleAjaxFailure(targetURL);
				}
			});
		},
	_showLoading: function() {
		var transitionGraphicHTML = '<div id="' + this.options.transitionGraphicID +'">'
									+ '<div><img id="transitionGraphicImg" src="' + this.options.protocol + this.options.loadingGraphicPath + '" /></div>'
									+ '</div>';
		jQuery('#' + this.options.targetID).parent().prepend(transitionGraphicHTML); 
		jQuery('#transitionGraphicImg').parent().css('marginLeft', jQuery('#transitionGraphicImg').width()/2*-1);
		jQuery('#' + this.options.transitionID).animate({opacity: 0.1}, this.options.fadeOutTimeout);
	},
	_hideLoading: function() {
		jQuery('#' + this.options.transitionID).css('opacity', 0.1);
		jQuery('#' + this.options.transitionID).animate({opacity: 1.0}, this.options.fadeInTimeout);
		jQuery('#' + this.options.transitionGraphicID).remove();
	},
	_afterDOMInsert: function(url, data) {
		this._hideLoading();
		this.handleAjaxSuccess(url, data);
		this._bindLinks();
		this._unbindEscIntercept();
	},
	_handleResponseScripts: function(data) {
		var sliderObj = this,
			dom = jQuery(data),
			responseScripts = [],
			output = [],
			scriptsProcessed = 0;
		jQuery.each(dom, function(index, value) {
			var scriptSrc = jQuery(value)[0].src;
			if (jQuery(value)[0].tagName == 'SCRIPT' && scriptSrc && jQuery.inArray(scriptSrc, sliderObj.options.loadedScripts) == -1) {
				responseScripts.push(this);
				sliderObj.options.loadedScripts.push(scriptSrc);
				scriptsProcessed++;
			} else if (jQuery.inArray(scriptSrc, sliderObj.options.loadedScripts) == -1) {
					output.push(this);
			}
		});
		return {scripts:responseScripts, data:output, scriptsToPreload:scriptsProcessed, scriptsLoaded:0};
	},
	_prepareHistory: function() {
		if (window.history.pushState) {
			var currentState = history.state;
			if (currentState === null || currentState === undefined) {
				window.history.replaceState(this.options.historyData, '', window.location.href);
			}
		}
	},
	_bindLinks : function(){
		if (window.history.pushState) {
			var sliderObj = this;
			jQuery('.' + this.options.bindingClass).bind('click', sliderObj, function (event) {
				var currentURL = window.location.href;
				var targetURL = this.href;
				targetURL = sliderObj.onClickDoFirst(targetURL, currentURL);
				window.history.pushState(sliderObj.options.historyData, '', targetURL);
				sliderObj._loadPage(targetURL);
				event.preventDefault();
			});
		}
	},
	_bindPopState : function() {
		var sliderObj = this;
		jQuery(window).bind('popstate', sliderObj, function(event) {
			if (event.originalEvent.state !== null) {
				var urlForSlide = location.href;
				sliderObj._loadPage(urlForSlide);
			}
		});
	},
	_unbindLinks : function() {
		jQuery('.' + this.options.bindingClass).unbind('click');
	},
	_bindUnload: function() {	
		if (window.history.pushState) {
			jQuery(window).bind('beforeunload', function() {
				jQuery(window).unbind('popstate');
				//window.history.replaceState(null, '', window.location.href);
			});
		}
	},
	_bindEscIntercept: function() {
		jQuery(document).bind('keydown', function(event) {
			if (event.keyCode == 27) {
				event.preventDefault();
			}
		});
	},
	_unbindEscIntercept : function() {
		jQuery(document).unbind('keydown');
	}

});
$.plugin('slidepage', SlidePage);



var IF_SlidePage = SlidePage.extend({
	handleAjaxSuccess: function(url, data) {
		var pageTitle = jQuery('#title_partial').html();
		if (pageTitle) {
			document.title = pageTitle;
			jQuery('#BreadcrumbPageTitle').html(pageTitle);
		}
		jQuery('#title_partial').remove();
		this.handleAnalytics(); 
	},
	handleAnalytics: function() {
		var analyticsCall = '<script language="JavaScript"'
							+ 'src="http://www.ifriends.net/global/js/GoogleAnalyticsInvoke.js"'
							+ 'type="Text/JavaScript"></sc'
							+ 'ript>';
		jQuery('body').prepend(analyticsCall);
	}
});
$.plugin('if_slidepage', IF_SlidePage);




var FC_SlidePage = IF_SlidePage.extend({
	handleAjaxSuccess: function(url, data) {
		this._super(url, data);
		iframeModalUnbind();
		jQuery('#fc-button-parent').html(jQuery('#fc-button-partial').html());
		jQuery('#fc-button-partial').remove();
		jQuery('#fc-sideBarVHModule').html(jQuery('#fc-sidebar-partial').html());
		jQuery('#fc-sidebar-partial').remove();
		iframeModalBind();
	},
	onClickDoFirst: function(targetURL, currentURL) {
		if (jQuery('#fc-mydressingroomMore').css('display') == 'none') {
			targetURL += '&pSideBarDisplay=Expanded';
		} else if (jQuery('#fc-mydressingroomCollapse').css('display') == 'none') {
			targetURL += '&pSideBarDisplay=Collapsed';
		}

		if (currentURL.search(/pvchedit=true/i) !== -1 && targetURL.search(/pvchedit=false/i) == -1) {
			targetURL += "&pVCHEdit=true";
		} 
		return targetURL;
	}
});
$.plugin('fc_slidepage', FC_SlidePage);
