// JavaScript Document
function loadHome(){
	loadSection("home.cfm");
}
function loadSection(section) {
	var url = section;
	
	function successHandler(obj) {
		// Use the response...
		YAHOO.util.Dom.get("content").innerHTML = obj.responseText;
		processContent();
		refreshLoginPanel();
		scroll(0,0);
		//pageTracker._trackPageview(url);
	}

	function failureHandler(obj) {
		// Fallback...
		location.href = section;
	}
	
	YAHOO.util.Connect.asyncRequest("GET", url,
		{
				cache:false,
				success:successHandler,
				failure:failureHandler
		}
	);
	
	YAHOO.util.Connect.startEvent.subscribe(function(){
		waitPanel.show();
	});
	
	YAHOO.util.Connect.completeEvent.subscribe(function(){
		waitPanel.hide();
	});
}

function runSearch(section, fieldName) {
	var url = section + '?keywords=' + document.forms[fieldName].keywords.value;
	
	YAHOO.util.History.navigate("MP_Page", url);
	
}

function loadCustomSection(section, id) {
	var url = section;
	
	function successHandler(obj) {
		// Use the response...
		scroll(0,0);
		YAHOO.util.Dom.get(id).innerHTML = obj.responseText;
		processCustomContent(id);
	}

	function failureHandler(obj) {
		// Fallback...
		location.href = section;
	}
	
	YAHOO.util.Connect.asyncRequest("GET", url,
		{
				cache:false,
				success:successHandler,
				failure:failureHandler
		}
	);
	
	YAHOO.util.Connect.startEvent.subscribe(function(){
		waitPanel.show();
	});
	
	YAHOO.util.Connect.completeEvent.subscribe(function(){
		waitPanel.hide();
	});
}

function loadSectionByPost(section, formID) {
	var url = section;
	
	YAHOO.util.Connect.setForm(formID);
	
	function successHandler(obj) {
		// Use the response...
		scroll(0,0);
		YAHOO.util.Dom.get("content").innerHTML = obj.responseText;
		processContent();
		//YAHOO.util.Dom.get("content").style.visibility = "visible";
		waitPanel.hide();
	}

	function failureHandler(obj) {
		// Fallback...
		//location.href = section;
	}
	
	//YAHOO.util.Dom.get("content").style.visibility = "hidden";
	waitPanel.show();
	
	YAHOO.util.Connect.asyncRequest("POST", url,
			{
				cache:false,
				success:successHandler,
				failure:failureHandler
			}
		);
}

function finishChangePWDByPost(section, formID) {
	var url = section;
	
	YAHOO.util.Connect.setForm(formID);
	
	function successHandler(obj) {
		// Use the response...
		var ck = YAHOO.util.Cookie.getSub("CFCLIENT_MINESPRESS_WEBAPP","customerid");

		if (ck != 0) {
			loadSection("MyAccount.cfm");
			loadCustomSection("LoginModule.cfm","LoginPanel");
		}
		else {
			YAHOO.util.Dom.get("content").innerHTML = obj.responseText;
			processContent();
			//YAHOO.util.Dom.get("content").style.visibility = "visible";
			waitPanel.hide();
		}
	}

	function failureHandler(obj) {
		// Fallback...
		//location.href = section;
	}
	
	//YAHOO.util.Dom.get("content").style.visibility = "hidden";
	waitPanel.show();
	
	YAHOO.util.Connect.asyncRequest("POST", url,
			{
				cache:false,
				success:successHandler,
				failure:failureHandler
			}
		);
}

function updateCartByPost(section, formID){
	var url = section;
	waitPanel.show();
	
	YAHOO.util.Connect.setForm(formID);
	
	function successHandler(obj) {
		// Use the response...
		scroll(0,0);
		waitPanel.hide();
		YAHOO.util.Dom.get("content").innerHTML = obj.responseText;
		processContent();
		reloadCart();
	}

	function failureHandler(obj) {
		// Fallback...
		//location.href = section;
	}
	
	YAHOO.util.Connect.asyncRequest("POST", url,
			{
				cache:false,
				success:successHandler,
				failure:failureHandler
			}
		);
}

function addToCartByPost(section, formID){
	var url = section;
	var imprintEl = "";
	imprintEl = YAHOO.util.Dom.get("info_option_1");

	YAHOO.util.Connect.setForm(formID);
	
	
	function successHandler(obj) {
		// Use the response...
		scroll(0,0);
		waitPanel.hide();
		YAHOO.util.Dom.get("content").innerHTML = obj.responseText;
		processContent();
		reloadCart();
		if (YAHOO.util.Dom.get("errorMessage").innerHTML == '') {
			addToCartDialog.show();
		}
	}

	function failureHandler(obj) {
		// Fallback...
		//location.href = section;
	}

		waitPanel.show();
		YAHOO.util.Connect.asyncRequest("POST", url, {
			cache: false,
			success: successHandler,
			failure: failureHandler
		});
	//}
	
}

function processContent() {
	
	//flashapps = YAHOO.util.Dom.getElementsByClassName('AjaxFlash','div','content');
	if(YAHOO.util.Dom.inDocument('pageTitle')){
		document.title = YAHOO.util.Dom.get('pageTitle').innerHTML;
	}
	anchors = YAHOO.util.Dom.get('content').getElementsByTagName('a');
	setCustomAjaxTabItems();
	//setCustomAjaxFlashItems(flashapps);
	setCustomAjaxNavItems(anchors);
	/*if(YAHOO.util.History.getCurrentState("MP_Page") == "home.cfm"){
		loadFrontPanel();
	}*/
	
}

function processCustomContent(id) {
	
	//flashapps = YAHOO.util.Dom.getElementsByClassName('AjaxFlash','div','content');
	anchors = YAHOO.util.Dom.get(id).getElementsByTagName('a');
	setCustomAjaxNavItems(anchors);
	
}

function loadLoginByPost(section, formID) {
	var url = section;
	
	YAHOO.util.Connect.setForm(formID);
	
	function successHandler(obj) {
		// Use the response...
		scroll(0,0);
		YAHOO.util.Dom.get("content").innerHTML = obj.responseText;
		processContent();
		YAHOO.util.Dom.get("content").style.visibility = "visible";
		waitPanel.hide();
		refreshLoginPanel('LoginModule.cfm');
		
		
	}

	function failureHandler(obj) {
		// Fallback...
		//location.href = section;
	}
	
	YAHOO.util.Dom.get("content").style.visibility = "hidden";
	waitPanel.show();
	
	YAHOO.util.Connect.asyncRequest("POST", url,
			{
				cache:false,
				success:successHandler,
				failure:failureHandler
			}
		);
}

function refreshLoginPanel(location){
	
	var section = 'LoginModule.cfm';
	
	function successHandler(obj) {
		// Use the response...
		YAHOO.util.Dom.get("LoginPanel").innerHTML = obj.responseText;
		processCustomContent("LoginPanel");
		
	}

	function failureHandler(obj) {
		// Fallback...
		location.href = section;
	}
	
	YAHOO.util.Connect.asyncRequest("GET", section,
			{
				cache:false,
				success:successHandler,
				failure:failureHandler
			}
		);
}

//function logout(){

	//refreshLoginPanel('yy');
	//loadSection('ShowCart.cfm?logout=yes');
//}
/*function initLoginModule(){
	
	var verifyun;
	
	var handleSubmit = function() {
		verifyun = this.getData();
		this.submit();
	};
	var handleCancel = function() {
		this.cancel();
	};
	
	var handleRegister = function() {
		loadSection('MyAccount.cfm');
		this.cancel();
	};

	var handleSuccess = function(o) {
	var response = o.responseText;
	if (response == '') {
		loginDialog.setBody('<p>We\'re sorry, we were unable to log you in at this time.<br>If you are a new user you may register for free at any time!</p>' + '<form method="POST" action="LoginModule.cfm">' +
		'<input name="retcustomer" type="hidden" value="yes" />' +
        '<label for="username">Username:</label>&nbsp;&nbsp;<input name="username" id="username" type="text" />' +
        '<div class="clear" style="margin-top:3px;"></div>' +
        '<label for="password">Password:</label>&nbsp;&nbsp;<input name="password" id="password" type="password" />' +
        '<div class="clear" style="margin-top:3px;"></div></form>');
	}
	else {
		if (response == 'verify ') {
			loadSection("erpIntegration.cfm?username=" + verifyun.username);
			loginDialog.hide();
		}
		else {
			document.getElementById("LoginPanel").innerHTML = response;
			anchors = YAHOO.util.Dom.get('LoginPanel').getElementsByTagName('a');
			setCustomAjaxNavItems(anchors);
			if (YAHOO.util.History.getCurrentState("MP_Page") != "home.cfm") {
				loadSection(YAHOO.util.History.getCurrentState("MP_Page"));
			}
			loginDialog.hide();
		}
	}
	};

	var handleFailure = function(o) {
	alert("Submission failed: " + o.status);
	};
	
	// Instantiate the Dialog
	loginDialog = new YAHOO.widget.Dialog("LoginModule", 
		{ 	width : "340px",
			height : "160px",
			fixedcenter : true,
			visible : false, 
			constraintoviewport : true,
			draggable: true,
			zindex:100,
			modal: true,
			close: false,
			hideaftersubmit: false,
			effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.5},
			buttons : [ { text:"Login", handler:handleSubmit, isDefault:true },
						  { text:"Close", handler:handleCancel },
						  { text: "Register", handler:handleRegister } ]
		} );
	loginDialog.setHeader('Login - Enter Information');
	loginDialog.setBody('<form method="POST" action="LoginModule.cfm">' +
		'<input name="retcustomer" type="hidden" value="yes" />' +
        '<label for="username">Username:</label>&nbsp;&nbsp;<input name="username" id="username" type="text" />' +
        '<div class="clear" style="margin-top:3px;"></div>' +
        '<label for="password">Password:</label>&nbsp;&nbsp;<input name="password" id="password" type="password" />' +
        '<div class="clear" style="margin-top:3px;"></div></form>');
		
	// Define various event handlers for Dialog

	loginDialog.callback = { success: handleSuccess,
							 failure: handleFailure };
	
	loginDialog.render();
							 
	YAHOO.util.Event.addListener("showLogin", "click", loginDialog.show, loginDialog, true);
}
*/
function reloadCart() {
	
	YAHOO.util.Connect.asyncRequest("GET", "cw3/CWTags/CWTagCartLinks.cfm",
		{
			cache:false,
			success:function(o){ 
			
				YAHOO.util.Dom.get("CartModule").innerHTML = o.responseText;
				anchors = YAHOO.util.Dom.get('CartModule').getElementsByTagName('a');
				setCustomAjaxNavItems(anchors);
			 },
			failure: function(o) { }
		}
	);
}


function setCustomAjaxTabItems(){

	tabPanel = YAHOO.util.Dom.get('prodDetails');
	if (tabPanel != null) {
	
		tabView = new YAHOO.widget.TabView(tabPanel.id);
		
		tabView.addListener("activeTabChange", handleTabViewActiveTabChange);
	}

}

function setCustomAjaxFlashItems(flashapps) {

	var i, len;
	
	var flashvars = {};
	var params = {
		wmode:"transparent"
	};
	var attributes = {};
	
	for(i = 0, len = flashapps.length; i < len; i++) {
		
		moviename = flashapps[i].innerHTML;
		
		swfobject.embedSWF(moviename + ".swf", flashapps[i].getAttribute('id'), flashapps[i].getAttribute('width'),flashapps[i].getAttribute('height'), "9.0.0",null,flashvars,params,attributes);		
	}
	
}

function setCustomAjaxNavItems(anchors) {
	
	var i, len, anchor, href, section, currentSection;
	
	for (i = 0, len = anchors.length; i < len; i++) {
		anchor = anchors[i];
		
		if(anchor.className == 'nav') {
		
			YAHOO.util.Event.addListener(anchor, "click", function (evt) {
				href = this.getAttribute("href");
				section = href;
				// If the Browser History Manager was not successfuly initialized,
				// the following call to YAHOO.util.History.navigate will throw an
				// exception. We need to catch it and update the UI. The only
				// problem is that this new state will not be added to the browser
				// history.
				//
				// Another solution is to make sure this is an A-grade browser.
				// In that case, under normal circumstances, no exception should
				// be thrown here.
				try {
					YAHOO.util.History.navigate("MP_Page", section);
				} catch (e) {
					loadSection(section);
				}
				YAHOO.util.Event.preventDefault(evt);
			});	
		}
	}
}

function handleTabViewActiveTabChange (e) {
	
        var newState, currentState;

        newState = "tab" + this.getTabIndex(e.newValue);

        try {
			currentState = YAHOO.util.History.getCurrentState("tabView");
			// The following test is crucial. Otherwise, we end up circling forever.
			// Indeed, YAHOO.util.History.navigate will call the module onStateChange
			// callback, which will call tabView.set, which will call this handler
			// and it keeps going from here...
			if (newState != currentState) {
				YAHOO.util.History.navigate("tabView", newState);
			}
		} 
		catch (e) {
			this.set("activeIndex", newState.substr(3));
		}
}

function initializeNavigationBar() {
	// Process links
	var anchors, i, len, anchor, href, section, currentSection;
	anchors = YAHOO.util.Dom.getElementsByClassName('nav','a');
	for (i = 0, len = anchors.length; i < len; i++) {
		anchor = anchors[i];
		
		YAHOO.util.Event.addListener(anchor, "click", function (evt) {
			href = this.getAttribute("href");
			section = href || "home.cfm";
			// If the Browser History Manager was not successfuly initialized,
			// the following call to YAHOO.util.History.navigate will throw an
			// exception. We need to catch it and update the UI. The only
			// problem is that this new state will not be added to the browser
			// history.
			//
			// Another solution is to make sure this is an A-grade browser.
			// In that case, under normal circumstances, no exception should
			// be thrown here.
			try {
				YAHOO.util.History.navigate("MP_Page", section);
			} catch (e) {
				loadSection(section);		
			}
			YAHOO.util.Event.preventDefault(evt);
		});
	}

	// This is the tricky part... The window's onload handler is called when the
	// user comes back to your page using the back button. In this case, the
	// actual section that needs to be loaded corresponds to the last section
	// visited before leaving the page, and not the initial section. This can
	// be retrieved using getCurrentState:
	currentSection = YAHOO.util.History.getCurrentState("MP_Page");
	loadSection(currentSection);
}

function initHistory() {
	// Initialize the browser history management library.
	try {
		YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");
	} catch (e) {
		// The only exception that gets thrown here is when the browser is
		// not supported (Opera, or not A-grade) Degrade gracefully.
		// Note that we have two options here to degrade gracefully:
		//   1) Call initializeNavigationBar. The page will use Ajax/DHTML,
		//      but the back/forward buttons will not work.
		//   2) Initialize our module. The page will not use Ajax/DHTML,
		//      but the back/forward buttons will work. This is what we
		//      chose to do here:
		loadSection(initialSection);
	}

}


function createExtImageViewer(windowname, windowtitle, imagepath ) {
	
	var url = "cw3/CWIncCreateImgPanel.cfm?imagepath=" + imagepath;
	
	// Instantiate a Panel from script '<img src="' + imagepath + '" />'
	
	function successHandler(obj) {
		// Use the response...

		extImgPanel = new YAHOO.widget.Panel(windowname, { width:"620px", height:"620px",fixedcenter:false,zindex:100, visible:false,modal:true,effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.5}, draggable:true, close:true } );
		extImgPanel.setHeader(windowtitle);
		extImgPanel.setBody(obj.responseText);
		extImgPanel.render(document.body);

	
		function getImage(parent) {
		  var el = parent.firstChild;
		  
		  while (el) {  // walk through till as long as there's an element
			if (el.nodeName.toUpperCase() == "IMG") { // found an image
			  // flickr uses "_s" suffix for small, and "_m" for big images respectively
			  return el.src.replace(/_thumb\.jpg$/, ".jpg");
			}
			el = el.nextSibling;
		  }
		  
		  return "";
		}
				
		YAHOO.util.Event.onContentReady("carousel",function () {
		var spotlight = YAHOO.util.Dom.get("spotlight");
		var carousel = new YAHOO.widget.Carousel("carousel",{numVisible:7});
		  carousel.on("itemSelected", function (index) {
			var item = carousel.getElementForItem(index);
		
			if (item) {
				spotlight.innerHTML = "<img src=\"" + getImage(item) + "\">";
			}
		  });
		  carousel.render(); // get ready for rendering the widget
		  carousel.show();   // display the widget
	    });
		
		hideCarousel = function(type){
			var e = document.getElementById('imagePanel');
			e.innerHTML = "";
		}
		extImgPanel.hideEvent.subscribe(hideCarousel);
		/*var handlePrevButtonState = function(type, args) {

		    var enabling = args[0];
		    var leftImage = args[1];
		    if(enabling) {
		        leftImage.src = "../../images/left_enabled.png";    
		    } else {
		        leftImage.src = "../../images/left_disabled.png";    
		    }
    
		};
		
		var handleNextButtonState = function(type, args) {
		
		    var enabling = args[0];
		    var rightImage = args[1];
		    
		    if(enabling) {
		        rightImage.src = "../../images/right_enabled.png";
		    } else {
		        rightImage.src = "../../images/right_disabled.png";
		    }
		    
		};
		
		var handleInit = function(){
			//carousel.calculateSize();
		}
		
		isCarouselDefined = YAHOO.util.Dom.get("mycarousel");

		if(isCarouselDefined != null){

			carousel = new YAHOO.extension.Carousel("mycarousel", 
				{
				numVisible:        5,
				animationSpeed:    0.25,
				scrollInc:         1,
				navMargin:         20,
				prevElement:     "prev-arrow",
				nextElement:     "next-arrow",
				Size:14,
				prevButtonStateHandler:   handlePrevButtonState,
				nextButtonStateHandler:   handleNextButtonState,
				loadInitHandler: handleInit
				}
			);
		
		}*/
		
		extImgPanel.show();
	}

	function failureHandler(obj) {
		// Fallback...
		//location.href = section;
	}
	
	YAHOO.util.Connect.asyncRequest("GET", url,
		{
				cache:false,
				success:successHandler,
				failure:failureHandler
		}
	);
}

// Instantiate the Dialog
function init(){

	var bookmarkedSection = YAHOO.util.History.getBookmarkedState("MP_Page");
	var querySection = YAHOO.util.History.getQueryStringParameter("section");
	var initialSection = bookmarkedSection || querySection || "home.cfm";
	var bookmarkedTabViewState = YAHOO.util.History.getBookmarkedState("tabview");
	var initialTabViewState = bookmarkedTabViewState|| "tab0";	
	
	YAHOO.util.History.register("MP_Page", initialSection, function (state) {
		// Load the appropriate section:
		loadSection(state);
	});
	
	YAHOO.util.History.register("tabView", initialTabViewState, function (state) {
	    // This is called after calling YAHOO.util.History.navigate, or after the user
	    // has trigerred the back/forward button. We cannot discrminate between
	    // these two situations.
	
	    // "state" can be "tab0", "tab1" or "tab2".
	    // Select the right tab:
		if (YAHOO.util.History.getCurrentState("MP_Page") != "home.cfm") {
			tabView.set("activeIndex", state.substr(3));
		}
	});

	YAHOO.util.History.onReady(function () {
		initializeNavigationBar();
	});
	
	//initLoginModule();
	
		var handleContinue = function(){
			this.hide();
		};
		
		var handleCart = function(){
			this.hide();
			loadSection('ShowCart.cfm');
		}
		
		addToCartDialog =
		new YAHOO.widget.SimpleDialog("addCartDlg",
			{ width: "375px",
			  fixedcenter: true,
			  modal: true,
			  visible: false,
			  draggable: false,
			  close: false,
			  zindex:1000,
			  text: "Product added. What would you like to do?",
			  effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.10},
			  buttons: [{text:"Continue Shopping", handler:handleContinue, isDefault:true },
			  			{text:"Proceed To Cart", handler:handleCart} ]		
			});
		
		addToCartDialog.render(document.body);

		
		// Initialize the temporary Panel to display while waiting for external content to load
	waitPanel  = 
		new YAHOO.widget.Panel("wait",  
			{ width:"240px", 
			  fixedcenter:true, 
			  close:false, 
			  draggable:false, 
			  zindex:1000,
			  effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.10},
			  visible:false
			} 
		);

	/*waitPanel.hideEvent.subscribe(function(){
		YAHOO.util.Dom.get("content").style.visibility = "visible";
	});
	waitPanel.beforeShowEvent.subscribe( function(){
		YAHOO.util.Dom.get("content").style.visibility = "hidden";
	});*/
	waitPanel.setHeader("Loading, please wait...");
	waitPanel.setBody('<img src="../../images/rel_interstitial_loading.gif" />');
	waitPanel.render(document.body);

	
	document.getElementById("wrapper").style.visibility = "visible";
	reloadCart();

}

YAHOO.util.Event.onDOMReady(init);