var _resultsOfLastQuery = "";
var _PromoEngineLoopCounter = 0;

function PromoEngine(values)
{
	alert("new PromoEngine");
	
	// iterate through all the configurations and populate local variables
	for (var n in values) 
	{ 
		//alert( n );
		this[n] = values[n]; 
	}
	
}

//curent promotions in JSON format
PromoEngine.currentPromotions

//curent promotion in JSON format
PromoEngine.currentPromotion

//the div in the main window that will contain all the promotion tabs
PromoEngine.divPromoTabDetailsContainer = "divPromoTabDetails";

PromoEngine.iframeDivId = "divIframePromoTab";
PromoEngine.getIframeDivId = function() { return this.iframeDivId; }
PromoEngine.setIframeDivId = function(x) { this.iframeDivId = x; }


//asks rails for a specific URL - which will then use RJS to update the page
//  why???  because we allow rails to iterate over models with assosication (weburls :has_many => promotions)
PromoEngine.getPromotionsByURL = function (x)
{
	var _request = new Ajax.Request("/weburls/show", 
	{
		method: "get",
		parameters: "URL=" + x,
		onSuccess: PromoEngine.getPromotionsByURLSuccess //,
		//onError: UserBookmarks.addBookmarkError
	});
}


PromoEngine.getPromotionsByURLSuccess  = function(x)
{
	// if you got new promotions, you CAN'T HAVE A CURRENT PROMOTION
	PromoEngine.currentPromotion = '';
}



PromoEngine.getPromotion = function(x) //this is second
{
	// get the details on the promotion
	PromoEngine.moveTabBack(x)
	
	var _request = new Ajax.Request("/promotions/" + x + ".json", 
	{
		method: "get",
		params: "format=json",
		onSuccess: PromoEngine.getPromotionSuccess
		// onError: PromoEngine.renderDetailsWindowSuccess
	});
}


PromoEngine.getPromotionSuccess = function(x)
{
	//alert("renderDetailsWindowSuccess: " + x.responseText);
	var _result = x.responseText.evalJSON();
	var _randomNumber = Math.ceil(100*Math.random());
	
	//set the currently located promotion statically
	PromoEngine.currentPromotion = _result;
	
	PromoEngine.renderPromoDetailsWindow();

}


PromoEngine.renderPromoDetailsWindow = function()
{
	//alert("PromoEngine.renderPromoDetailsWindow");
	
	var _randomNumber = Math.ceil(100*Math.random());
	var _fileType = "png";
	var _divWithShadows = '';
	var _closeDivWithShadows = '';

	// safari loves to cache iframes... so make a unqiue id each pass
	PromoEngine.iframeDivId = _randomNumber;
		
	try
	{
		PromoEngine.destroyPromoTabDetailsChildren();
	}
	catch (Exception)
	{
		//alert('ouchy... i fell down trying to remove the promoengine.iframe from the dom...');
	}

	if ( Utility.isIE() && Utility.browserVersion() <= 6)
	{
		_fileType = "gif";
	}	
	
	var _closeButton = '<div id="divPromoTabDetailsWindowCloseBox"><img src="/universal/images/promoTabs/closeBox.' + _fileType + '" onclick="javascript:PromoEngine.closeDetailWindow(' + PromoEngine.currentPromotion.id + ');"></div>'

	
	var _promotionShadowContainer = '<div class="cb" id="divPromoDetailsWindowShadowContainer">'
	var _closePromotionShadowContainer = '</div>'
	
	_divWithShadows = '<div class="" id="divPromoDetailsWindowShadow"><image id="imgPromoDetailsWindowShadow" src="/universal/images/promoTabs/detailsWindowShadow.' + _fileType + '">';
	_closeDivWithShadows = '</div>';
	
	var _iframe = "<iframe id='" + PromoEngine.iframeDivId + "' src='/universal/apps/promotions/" + PromoEngine.currentPromotion.promo_directory_name + "/index.htm?" + _randomNumber + "' marginwidth='0' marginheight='0' scrolling='no' frameborder='0' allowtransparency='false' vspace='0' hspace='0' noresize='noresize' style='display:none;'></iframe>";
	//var _iframe = "<iframe id='" + PromoEngine.iframeDivId + "' marginwidth='0' marginheight='0' scrolling='no' frameborder='0' allowtransparency='true' style='display:none;z-index:2;position:absolute;left:55px;top:60px;'></iframe>";

	var _table = '<table border="0" cellspacing="0" cellpadding="0"> \
	 <tr> \
	   <td height="56"><img id="imgPromoTabDetailsWindowShadowTopLeft" src="/universal/images/promoTabs/shadowTopLeft.png" width="61" height="56" /></td> \
	   <td height="56"><img id="imgPromoTabDetailsWindowShadowTop" src="/universal/images/promoTabs/shadowTop.png" width="100%" height="56" /></td> \
	   <td height="56"><img id="imgPromoTabDetailsWindowShadowTopRight" src="/universal/images/promoTabs/shadowTopRight.png" width="64" height="56" /></td> \
	 </tr> \
	 <tr> \
	   <td><img id="imgPromoTabDetailsWindowShadowLeft" src="/universal/images/promoTabs/shadowLeft.png" width="61" /></td> \
	   <td id="tdIframeCell">' + _iframe + '</td> \
	   <td><img id="imgPromoTabDetailsWindowShadowRight" src="/universal/images/promoTabs/shadowRight.png" width="64" /></td> \
	 </tr> \
	 <tr> \
	   <td height="49"><img id="imgPromoTabDetailsWindowShadowBottomLeft" src="/universal/images/promoTabs/shadowBottomLeft.png" width="61" height="49" /></td> \
	   <td height="49"><img id="imgPromoTabDetailsWindowShadowBottom" src="/universal/images/promoTabs/shadowBottom.png" width="100%" height="49" /></td> \
	   <td height="49"><img id="imgPromoTabDetailsWindowShadowBottomRight" src="/universal/images/promoTabs/shadowBottomRight.png" width="64" height="49" /></td> \
	 </tr> \
	</table>';

	// add to DOM
	document.getElementById( PromoEngine.divPromoTabDetailsContainer ).innerHTML = _closeButton + _table;
	
	//alert("exiting PromoEngine.renderPromoDetailsWindow");
}



PromoEngine.resizeIframe = function(w,h)
{
	
	//alert("PromoEngine.resizeIframe called: " + w + " " + h);
	document.getElementById(PromoEngine.iframeDivId).style.width = w + "px";
	document.getElementById(PromoEngine.iframeDivId).style.height = h + "px";

}

PromoEngine.resizeDetailsWindowBackgroundImage = function(w,h)
{
	//document.getElementById('imgPromoDetailsWindowShadow').style.width= (w + (w*.30) ) + "px";
	//document.getElementById('imgPromoDetailsWindowShadow').style.height= (h + (w*.30) ) + "px";
	
	document.getElementById('imgPromoDetailsWindowShadow').style.width= (w + 100 ) + "px";
	document.getElementById('imgPromoDetailsWindowShadow').style.height= (h + 100 ) + "px";
	
}

PromoEngine.hideDetailsWindowBackgroundImages = function()
{
	document.getElementById('imgPromoTabDetailsWindowShadowTopLeft').style.display="none";
	document.getElementById('imgPromoTabDetailsWindowShadowTop').style.display="none";
	document.getElementById('imgPromoTabDetailsWindowShadowTopRight').style.display="none";
	document.getElementById('imgPromoTabDetailsWindowShadowLeft').style.display="none";
	document.getElementById('imgPromoTabDetailsWindowShadowRight').style.display="none";
	document.getElementById('imgPromoTabDetailsWindowShadowBottomLeft').style.display="none";
	document.getElementById('imgPromoTabDetailsWindowShadowBottom').style.display="none";
	document.getElementById('imgPromoTabDetailsWindowShadowBottomRight').style.display="none";
}

PromoEngine.showDetailsWindowBackgroundImages = function()
{
	document.getElementById('imgPromoTabDetailsWindowShadowTopLeft').style.display="block";
	document.getElementById('imgPromoTabDetailsWindowShadowTop').style.display="block";
	document.getElementById('imgPromoTabDetailsWindowShadowTopRight').style.display="block";
	document.getElementById('imgPromoTabDetailsWindowShadowLeft').style.display="block";
	document.getElementById('imgPromoTabDetailsWindowShadowRight').style.display="block";
	document.getElementById('imgPromoTabDetailsWindowShadowBottomLeft').style.display="block";
	document.getElementById('imgPromoTabDetailsWindowShadowBottom').style.display="block";
	document.getElementById('imgPromoTabDetailsWindowShadowBottomRight').style.display="block";
}

// called when the promotion window page is completed
PromoEngine.childSiteLoadComplete = function(x,y,w,h)
{
	
	//alert("PromoEngine.childSiteLoadComplete..." + w + "x" + h);

	
	//position promotab window
	
	//resize window
	if ( (w == 0 || w > 910) || (h == 0 || h > 600) )
	{
		w = 450;
		h = 450;
	}
	
	// set iframe dimensions now that you have them
	PromoEngine.resizeIframe(w,h);

	// set drop shadow background dimensions now that you have them
	if (Utility.isIE() && Utility.browserVersion() <= 6)
	{
		PromoEngine.hideDetailsWindowBackgroundImages();
		document.getElementById(PromoEngine.iframeDivId).style.border="5px solid #333333";
	}
	else
	{	
		document.getElementById('imgPromoTabDetailsWindowShadowLeft').height = h;
		document.getElementById('imgPromoTabDetailsWindowShadowRight').height = h;
	}
	
	
	// the window has loaded - hide the loading dialog for the promotab, but still mark it as active
	document.getElementById("divPromoTab"+PromoEngine.currentPromotion.id).className="classPromoTabActive";
	
	
	//now move the div, then show it just above the tab that was clicked
	if ( PromoEngine.movePromoWindowAfterLoad(w, h) ) {
		//show promotab window
		//new Effect.Appear(document.getElementById(PromoEngine.divPromoTabDetailsContainer), {duration: 0.5} );		
	}
	
	PromoEngine.showDetailWindow();
	
	//alert("exiting PromoEngine.childSiteLoadComplete");
}



PromoEngine.renderLinkForDetailsWindow = function(x, passedTarget)
{
	if ( passedTarget == "_blank")
	{
		//Utility.message("PromoEngine","opening a new _blank window " + passedTarget,'info');
		window.parent.open(x);
		return;
	}
	
	if ( passedTarget == "_top")
	{
		//Utility.message("PromoEngine","opening page in _top window " + passedTarget,'info');
		window.parent.location = x;
		return;
	}
	
	//Utility.message("PromoEngine","opening a request in content window",'info');
	
	window.parent.window[_contentWindowMain].setURL(x);
	window.parent.PromoEngine.hideAllDetailWindows();
	window.parent.PromoEngine.destroyPromoTabDetailsChildren();
}



// makes sure we are removing ALL DOM elements inside the promotabdetails div
PromoEngine.destroyPromoTabDetailsChildren = function()
{
	var _divPromoTabDetails = document.getElementById(PromoEngine.divPromoTabDetailsContainer);
	
	if (_divPromoTabDetails.childNodes.length > 0)
	{
		_divPromoTabDetails.removeChild(_divPromoTabDetails.lastChild);
	}	
}

PromoEngine.showDetailWindow = function()
{
	Element.show(PromoEngine.divPromoTabDetailsContainer);

	new Effect.Appear(document.getElementById(PromoEngine.iframeDivId), {duration: 1.0} );
	//document.getElementById('divPromoDetailsWindowShadowContainer').style.display='block';
	
	
}


PromoEngine.closeDetailWindow = function(x)
{
	//PromoEngine.moveImageForward("divPromoTab"+x, "imgPromoTab"+x);
	new Effect.Fade("divPromoTabDetails", {duration:0.8})
	PromoEngine.destroyPromoTabDetailsChildren();
	PromoEngine.hideAllDetailWindows();
	document.getElementById("divPromoTab"+x).className="classPromoTab";
	PromoEngine.currentPromotion = '';
}


//note that we might want to ONLY hide and not destroy...
PromoEngine.hideAllDetailWindows = function()
{	
	Element.hide(document.getElementById(PromoEngine.divPromoTabDetailsContainer));
}


PromoEngine.activatePromoTab = function(passedPromoTabId)
{
	//alert("activatePromoTab for divPromoTab" + passedPromoTabId);
	
	try
	{
		var _result = eval(PromoEngine.currentPromotions);
	}
	catch(exception)
	{
		alert('ouch... ' + exception )
	}


	// loop through all promotions and only activate the one you passed in
	for(var x = 0; x < _result.length; x++)
	{
		var _x = "divPromoTab"+_result[x].id;
		
		if (_result[x].id == passedPromoTabId )
		{
			document.getElementById(_x).className="classPromoTabLoading";
		}
		else
		{
			document.getElementById(_x).className="classPromoTab";
		}
	}

}


PromoEngine.resetAllPromoTabs = function()
{
	
}


PromoEngine.movePromoWindowAfterLoad = function (w, h) {
	var c = document.getElementById("divPromoTab"+PromoEngine.currentPromotion.id);
	
	//setting the dimensions to make it appear just above the clicked tab
	var moveY = $(c.id).cumulativeOffset().top - (h + 128) //the height + some padding for style
	var moveX = $(c.id).cumulativeOffset().left - 20 //the position from the left of the browser window - some padding for drop shadow
	var tpt = c.getOffsetParent().childElements().length //total # of promotabs
	
	var promoOffSet = (tpt - c.nextSiblings().length) * 5 + moveX + 60
					//take total promo tabs, then find which one in the sequence was clicked
					// the cumulativeOffset does not take into account padding, so we must calc. that (5 px on one side)
					// Total padding + moveX tells us where the element is on the x axis on the screen
					// add 30 pixels to accomodate the X button and make sure it's not RIGHT on the edge of the screen
					
	//if new window is hanging outside the viewable screen... MOVE IT!
	
	if (Utility.isIE()) {
		//yet more code to please IE
		//alert(document.body.clientWidth)
		if ( w > (document.body.clientWidth - promoOffSet ) ) { 
			moveX -= (w - (document.body.clientWidth - promoOffSet) )
		}
	} else {
		//code for the standard compliant browsers
		if ( w > (window.innerWidth - promoOffSet ) ) { 
			moveX -= (w - (window.innerWidth - promoOffSet) )
		}
	}
	
	//move the new window from 0,0 (where it's rendered) to hover just above the clicked tab
	$("divPromoTabDetails").setStyle( {
		position: "absolute",
		top: moveY + "px",
		left: moveX + "px",
		width: w + 93 + "px",
		height: h + 93 + "px"
	})
	
	return true;
	
}


PromoEngine.moveTabBack = function(id) {
	//this moves the contained img out and shrinks it by 10% to give the effect of moving backwards

	// var divID = "divPromoTab"+id
	// var activeimage = $(divID).childElements()
	// var shrinkWidth = activeimage[0].getWidth() * 0.90
	// var shrinkHeight = activeimage[0].getHeight() * 0.90
	// new Effect.Morph(activeimage[0], {
	// 	style: {
	// 	   width: shrinkWidth + "px",
	// 	   height: shrinkHeight + "px",
	// 	   padding: "0 10px"
	// 	}
	// });
	// 
	// //each img is contained in a div with a shadow. This moves the div out
	// new Effect.Morph(divID, { //bring the clicked tab out a bit
	//   style: {
	// 	"margin-top": "-10px"
	//   }
	// });
}



//There are two times we'd want to move the image back to it's "normal" state: 1) when a user closes the promotab 2) user clicks another promotab
PromoEngine.moveImageForward = function(theDiv, theImg) {
	//remeber that there is a div that contains the shadow, and then the image itself
	// this moves them both
	new Effect.Morph(theDiv, {
		style: {
			"margin-top": "0px"
		}, 
		duration: 0.4})
	
	new Effect.Morph(theImg, {
		style: {
			width: "154px",
			height: "45px",
			padding: "0px"
		}, 
		duration: 0.4})
}

PromoEngine.logClickthrough = function(passedPromotionType, passedPromotionId, passedDestinationURL)
{
	var _request = new Ajax.Request("/promotions/" + passedPromotionId + "/promotionclickthroughs/", 
	{
		method: "post",
		parameters: "URL=" + passedDestinationURL + "&promotion_type=" + passedPromotionType,
		onSuccess: PromoEngine.getPromotionSuccess
		// onError: PromoEngine.renderDetailsWindowSuccess
	});
}


PromoEngine.getCurrentPromotionId = function()
{
	return PromoEngine.currentPromotion.id;
}