if(!argos) var argos = {}

argos.richercontent = new (function() {
	/****************************************
	1). Looks for any links with class .scene7
	2). Wraps children of found links parent (except itself and SCRIPT elements) in "nonRicherContent" DIV.
	3). Adds richerContent place holder DIV as sibling.
	4a). If user does not have flash version required: Populates richerContent with ajax'd noFlash message and inserted link.
			(activation of inserted link will remove "hidden" class from nonRicherContent DIV and add "hidden" class to 
			richerContent DIV - which has the effect of showing old content and hiding noFlash message+link).
	4b). If user does have flash version: Populates richerContent with ajax'd URL from scene7 href.
	******************************************/

	var _self = this;
	var _richerContentLinkSelector = ".scene7";
	var _richerContentSelector = ".richerContent";
	var _richerContentHidden = "richerContentHidden";
	var _richerContentRequestedBy = "";

	
	// PUBLIC FUNCTIONS

	this.init = function(context, requester) {
		// Richer content should not be invoked for HTTPS pages as it could be a security risk
		if(_self.hasRicherContent() && !argos.page.isSecurePage()) {
			var scene7 = context ? $(_richerContentLinkSelector, context) : $(_richerContentLinkSelector);
			var parent = scene7.parent();
			var version = scene7.attr("class").replace(/.*version_([0-9\.]*)/, "$1");
			var container = $("<div class=\"richerContent\"></div>");

			container.bind("mouseover", function() {
				_setRicherContentRequestedBy(requester);
			});

			parent.children().not("script, .scene7").wrapAll("<div class=\"nonRicherContent " + _richerContentHidden + "\"></div>"); 
			parent.append(container);

			if(_self.hasFlashVersion(version)) {
				_outputFlashContent(parent);
			}
			else {
				_outputNoFlashContent(parent);
			}

			parent.removeClass(_richerContentHidden);
		}
	}
	
	var PARAMETERIZED_EVENTS = ["VIDEO_PLAY_" ,"VIDEO_NAME_", "IMAGE_"];
	
	//Invoked by the Scene7 player to tag user actions inside scene7 content
	this.tagging = {}; // Populated in scene7Resources.
	this.tagEvent = function(evtAction, evtSource, evtName) {	    
		
		if("PopUp" == evtAction){
			evtAction = "Event";
			evtName = "POP_UP_VIEWER_OPEN";
			//evtSource ="";
		}
		
		if("Event" == evtAction){
			var s=s_gi(s_account);
			s.linkTrackVars = "";
			s.linkTrackEvents="";
			var tagKeys = _getTagKeys(evtName);			
			var saveParams = [];
			_debug("Found "+tagKeys.length+" tags for evtName="+evtName);
			for(var index in tagKeys){
				var tagKey = tagKeys[index];
				var tagValue = _self.tagging[tagKey];
				var tagName="";
				
				_debug(tagKey+"="+tagValue);
				if(tagValue){
					var tokens = tagValue.split(/\|/);
					if(tokens.length ==2){
						tagName=tokens[0];
						tagValue = tokens[1];
					}else{
						tagName=tokens[0];
						tagValue=evtName;
					}
					
					tagValue = _handleParameterizedEventNames(evtName, tagValue);
					saveParams[tagName] = s[tagName];
					s[tagName] = tagValue;
					_debug("s."+tagName+"="+tagValue+"");
					s.linkTrackVars =s.linkTrackVars+","+tagName;
					
					if("events"==tagName)s.linkTrackEvents=tagValue; 
				}
			}	
			_debug(s);			
			s.tl(this,'o',"Scene7 event");	
			_debug("*************************"+s.linkTrackVars);
			for(var index in saveParams){
				s[index] = saveParams[index];
				_debug(">>"+index+"="+saveParams[index]);
			}
			s.linkTrackVars ="";
			s.linkTrackEvents="";
		}
	}

	// Scene7 Richer Content Flash requirement check.
	this.hasFlashVersion = function(version) {
		var hasFlash=0;    
		var flashVersion=0;

		if($.browser.msie) {
			var swf;
			try { 
				swf = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
			}
			catch (e) {
				swf = null; // doesn't have flash or it's disabled.
			} 

			if(swf) {
				hasFlash=1;
				VSwf=swf.GetVariable("$version");
				flashVersion=parseFloat(VSwf.split(" ")[1].split(",")[0]); 
			}			
		}
		else {
			if (navigator.plugins && navigator.plugins.length > 0) {
				var swf=navigator.plugins["Shockwave Flash"];
			    if (swf) {
					hasFlash=1;
			        var words = swf.description.split(" ");
			        for (var i = 0; i < words.length; ++i) {
			            if (isNaN(parseInt(words[i]))) continue;
			            
				        if(parseInt(words[i]) < 10){
			            	flashVersion = '0'+words[i];
			            }else{
			            	flashVersion = words[i];
			            }
					}
			    }
			}
		}

		return (hasFlash && flashVersion.toString() >= version);
	}

	// Server logic renders element only if RC enabled.
	this.hasRicherContent = function() {
		return $(_richerContentLinkSelector).length > 0;
	}

	// Creates the popup for larger image and carousel flash objects
	this.open = function(URL,winName,features) {
		var newWindow=window.open(URL,winName,features);

		_closeOtherPopups();

		if(window.focus && newWindow) {
			newWindow.focus();
		}
	}

	// Returns String value representing the container/context of the clicked scene7 content 
	this.requestedBy = function() {
		return _richerContentRequestedBy;
	}

	// Get the current product that corresponds to the clicked scene7 content.
	this.product = function() {
		var qiProduct = argos.widgets.quickinfo.product();
		var pdpProduct = argos.pdp ? argos.pdp.product : {};
		var products = {
			"pdp" : {
				number : pdpProduct.number,
				shortDescription : pdpProduct.shortDescription,
				title : pdpProduct.title 
			},
			"quickinfo" : {
				number : qiProduct.number,
				shortDescription : qiProduct.shortDescription,
				title : qiProduct.title
			} 
		}

		return products[_richerContentRequestedBy] || {};
	}


	// PRIVATE FUNCTIONS

	function _debug(msg){	
		//if(true)console.debug(msg);
	}
	
	// Attempt to set a value for conditionals that need to handle actions according to the context.
	function _setRicherContentRequestedBy(requester) {
		_richerContentRequestedBy = requester;
	}
	
	
	/**********************
	This method replaces a %1 in tagvalue with corresponding parameter from evtName	
	**********************/	
	 function _handleParameterizedEventNames(evtName, tagValue){
	 	var newTagValue = tagValue;
	 	if(tagValue.indexOf("[%1]")>-1 ){
	 		var paramValue = "";
 			for( var index in PARAMETERIZED_EVENTS){
				if(evtName.indexOf(PARAMETERIZED_EVENTS[index])==0){
					paramValue = 	 evtName.replace(PARAMETERIZED_EVENTS[index], "");
 				}
	 		}
	 		if(paramValue != ""){
	 			newTagValue = tagValue.replace("\[%1\]", paramValue)+":";
	 		}
	 	}
	 	_debug("newTagValue: "+newTagValue);
	 	return newTagValue
	 	
	 }
	/**********************
	This method retrieves all keys of the form 
	SCENE7_TAGGING_CUSTOM_IMAGE_<evtName>
	SCENE7_TAGGING_CUSTOM_EVT_<evtName>
	with or without a suffix of type _1 till _100 ( ie SCENE7_TAGGING_CUSTOM_IMAGE_<evtName>_45 )	
	**********************/
	function _getTagKeys(evtName) {
		var tagKeys = [];
		var newEvtName = "";

		//if(newEvtName ==""){
			//If no parameterized event is found use default
			//newEvtName = "SCENE7_TAGGING_CUSTOM_EVT_"+evtName;
		//}
		if(_richerContentRequestedBy == "quickinfo"){
			newEvtName = "SCENE7_TAGGING_CUSTOM_EVT_QUICKVIEW_"+evtName;		
		}else{
			newEvtName = "SCENE7_TAGGING_CUSTOM_EVT_"+evtName;
		}
	
		var tagValue = _self.tagging[newEvtName];
	
		if(tagValue == null){
			for( var index in PARAMETERIZED_EVENTS){
				if(evtName.indexOf(PARAMETERIZED_EVENTS[index])==0){
					newEvtName = "SCENE7_TAGGING_CUSTOM_EVT_"+PARAMETERIZED_EVENTS[index]+"[%1]";
					break;
				}
			}
			tagValue = _self.tagging[newEvtName];
		}		
	
		 if(tagValue){
			tagKeys[0] = newEvtName;
		 }
	
		 for(var i =1; i<=100; i++){
			var tagKeyIndexed = newEvtName+"_"+i;
			if(!_self.tagging[tagKeyIndexed]){
				break;
			}
			tagKeys[tagKeys.length]  = tagKeyIndexed;
		 }
	
		return tagKeys;  
	}
	
	
	function _basicViewLoader() {
		var el = $("<a href=\"#basicImage\">View the standard product image</a>");
		el.click(function() {
			var parent = $(this).parent();
			parent.addClass("hidden");
			parent.siblings().removeClass("hidden");
			return false;
		});

		return el;
	}

	function _outputFlashContent(parent) {
		var scene7Link = $(_richerContentLinkSelector, parent);
		if(scene7Link.length > 0) {
			$.ajax({
				url : scene7Link.attr("href"),
				success : function (html) {
					$(_richerContentSelector, parent).append(html);
					parent.addClass("scene7FlashLoaded");
				}
			});
		}
	}

	function _outputNoFlashContent(parent) {
		$.ajax({
			url : "/argosincludes/richercontent/productDetailsNoFlashInstalled.htm",
			success : function (html) {
				var container = $(_richerContentSelector, parent);
				container.append(_basicViewLoader());
				container.append(html);
				container.addClass("noFlash");
			}
		});
	}

	function _closeOtherPopups() {
		// Add functionality here to close any open popups and LBs that we don't want to remain open.
		if(argos.popups) {
			argos.popups.close();
		}
	}

});


$(document).ready(function() {
	// Runs immediately on Product Details pages.
	// QuickInfo pages call this command to initiate.
	if(document.body.className.indexOf("productdetails") >= 0) { 
		argos.richercontent.init(document, "pdp");
	}
});


/* Legacy, third-party (Flash) calls viewerClickAction and EventInS7Content instead of argos.richercontent scoped functions directly */
function viewerClickAction(assetName) {
	// Called by scene7 Flash content.
	// Note: Investigation indicates this function is called via a try/catch with silent failure, by the Flash object. 
	//       This means any JS error contained within this function will not show as an error, and be very hard to locate!!
		var product = argos.richercontent.product(); 
		var storeId = argos.page.storeId;
		var partNumber = product.number.replace('\/', ''); 
		var shortDescription = product.shortDescription.replace('"', '\"');
		var title = product.title.replace('"', '\"');
		var data = "?storeId=" + storeId + "&assetName=" + assetName + "&partNumber=" + partNumber + "&shortDescription=" + shortDescription + "&title=" + title;
		var url = "/webapp/wcs/stores/servlet/Scene7RicherContentPopup" + data;
		var winName = "newRicherContentWindow";
		var features = "width=855,height=750,directories=no,location=no,menubar=no,scrollbars=yes,toolbar=no,status=no,resizable=yes,top=0,left=0"; 
		argos.richercontent.open(url, winName, features);
}
	
function EventInS7Content(inAssetSetName, inEvent, inAssetName, inEventName) {
	if("PopUp" == inEvent){
	    viewerClickAction(inAssetName);
	    return;
	}
	argos.richercontent.tagEvent(inEvent, inAssetSetName, inEventName);    	
}					


