/** Method that allows a calling function to explicitly
 * define a context that it wishes to execute in.
 * @param {Object} obj
 */
Function.prototype.bindObj = function(obj){
	//Handle to the calling function
	var method=this;

	//anonymous function that will execute the calling function
	//within the scope of the explicitly defined object
	scopeClosure = function(){
		//apply is a javascript method that immediately executes
		//a method in the scope of an explicitly defined object
		//this can not be directly invoked outside of the closure though
		//because we only want the method to be invoked when externally called
		//and not as the code is parsed by the browser.
		return method.apply(obj,arguments);
	};

	//reference to the call that executes in the second objects context
	return scopeClosure;
}

/** Class that deals with all client side locale switching issues for the TSS
 * Expext this class to be part of a call back from an ajax call as part of
 * switching languages on the page
 * @param {String} languageString
 */
function LocaleElement(languageString){
	//Class Variables
	var language = languageString;
	var frenchElement = document.getElementById("language:fr");
	var englishElement = document.getElementById("language:en");

	//Getter such that page language is globally available
	this.getLanguage = function(){
		return language;
	}

	/**
	 * Method that will verify the existence of the language selection
	 * page elements and then toggle them accordingly.  This is
	 * currently being updated via a basic remoting call.
	 */
	this.setLocaleStyle = function(){



		if (frenchElement === null ||
			englishElement === null) {
			return;
		}

		if (language == "fr"){

			frenchElement.className="current";
			frenchElement.disabled=true;
			frenchElement.href="#";
			frenchElement.onclick='return false;';
			frenchElement.style.cursor='text';
			frenchElement.style.textDecoration='none';

			englishElement.className="";
			englishElement.style.textDecoration='none';

		} else {
			frenchElement.className="";
			frenchElement.style.textDecoration='none';

			englishElement.className="current";
			englishElement.disabled=true;
			englishElement.href="#";
			englishElement.onclick='return false;';
			englishElement.style.cursor='text';
			englishElement.style.textDecoration='none';
		}
	}

	/**
	* Method to be used after an ajax call to verify the locale has not changed
	* in another location
	*/
	this.switchLocale = function(externalLink){
		/*alert(document.getElementById('TireDetails:localeSwitch').value);
		if (document.getElementById('TireDetails:localeSwitch').value == "true"){
			alert(document.getElementById('language:fr'));
			//document.getElementById('language').submit();
			Seam.Component.getInstance("tssDetailsBean").switchDetailsLocale(this.refreshPage.bindObj(localeElement));
		}*/
	}

	this.refreshPage = function(){
		//document.getElementById('language').submit();
	}
}

function updateLocaleCallback(language){
	localeElement = new LocaleElement(language);
	localeElement.setLocaleStyle();
}


function doTab(tab_number) {


	if (document.getElementById('tab_0F') != null){
		document.getElementById('tab_0F').className='off';
	}

	if (document.getElementById('tab_0R') != null){
		document.getElementById('tab_0R').className='off';
	}

	if (document.getElementById('tab_0B') != null){
		document.getElementById('tab_0B').className='off';
	}

	if (document.getElementById('tab_1F') != null){
		document.getElementById('tab_1F').className='off';
	}

	if (document.getElementById('tab_1R') != null){
		document.getElementById('tab_1R').className='off';
	}

	if (document.getElementById('tab_1B') != null){
		document.getElementById('tab_1B').className='off';
	}

	// these are for the details page
	if (document.getElementById('tab_1') != null){
		document.getElementById('tab_1').className='off';
	}

	if (document.getElementById('tab_2') != null){
		document.getElementById('tab_2').className='off';
	}

	if (document.getElementById('tab_3') != null){
		document.getElementById('tab_3').className='off';
	}

	var ele = document.getElementById(tab_number);
	if( ele ){
		ele.className='on';
	}
	return false;
}

function highlightInitialTab(){

	var uList = document.getElementById( 'resultsTabs' );
	if( uList ){

		var found = 0;
		var list = uList.getElementsByTagName('li');
		for( var i = 0; i < list.length; i++ ){

			var child = list[i];

				if( found == 0 ){
					child.className = 'on' ;
					found = 1 ;
				}
				else {
					child.className = 'off' ;
				}
		}
	}

}

/**
 *	Class that will deal with all client side aspects of the
 * 	selected comparison activities for tire results.
 */
function TrackComparisonItems(){

	/** Maximum number of tires that may be compared using TSS */
	var MAX_ITEMS_FOR_COMPARE = 3;
	/** Minimum number of tires that may be compared using TSS */
	var MIN_ITEMS_FOR_COMPARE = 2;
	/** Error message displayed when too many items are being selected for comapre */
	var MAX_ERR_MSG = document.getElementById('contentForm:compareErrorMessageMax').value;
	/** Error message displayed when too few items have been selected and compare is attempted */
	var MIN_ERR_MSG = document.getElementById('contentForm:compareErrorMessageMin').value;



	/**
	 * The trackItems method is responsible for keeping a count of the selected items
	 * for a given tire type.  If more than the maximum - 3 in this case are selected
	 * an alert box will display the error and the check box selected will automatically
	 * be unchecked.

	 NOTE: This method also syncs the checkbox statuses back to the TSSBean
	 */
	this.trackItems = function(element, cpn ){

		var retVal=true;

		var numberOfItemsSelected = this.getNumberOfItemsSelected()

		//If the user has attempted to add another item to compare
		if (element.checked) {
			//First ensure that the maximum number of comparison items has not
			//been already reached
			if (numberOfItemsSelected > MAX_ITEMS_FOR_COMPARE){
				alert(MAX_ERR_MSG);
				element.checked=false;
				retVal = false;
			}
			//If there are fewer than the maximum number of comparable items selected
			//then increment the number of items being compared and store to the form
			else {
				element.checked=true;
				retVal = true;
			}
		}

		Seam.Component.getInstance("tssBean").setFitmentSelectionState(
			cpn, element.checked.toString(), setFitmentSelectionStateCallback );

		return retVal ;
	}

	function setFitmentSelectionStateCallback(){
		// just in case we need the call back
	}

	// returns the number of selected items on the current page
	this.getNumberOfItemsSelected = function(){

		var numChecked = 0 ;

		// this will get the compare checkboxes
		var checkboxes = $(".tire_compare input[type='checkbox']")
		for( var i = 0; i < checkboxes.length; i++ ){
			var box = checkboxes.get(i)
			if( $(box).attr('checked') == true ){
				numChecked++;
			}
		}

		return numChecked;
	}

	// returns the number of selected items on the current page
	this.getItemsSelectedCPNs = function(){

		var selectedCPNs = "" ;

		// this will get the compare checkboxes
		var checkboxes = $(".tire_compare input[type='checkbox']")
		for( var i = 0; i < checkboxes.length; i++ ){

			var box = checkboxes.get(i)
			if( $(box).attr('checked') == true ){
				var lbl = $(box).next( 'label' )
				var lblid = $(lbl).attr('id')
				var pos = lblid.indexOf('_')
				var cpn = lblid.substring( ( pos + 1 ) )
				if( cpn ){
					selectedCPNs = selectedCPNs +','+ cpn
				}
			}
		}
		return selectedCPNs;
	}

	/**
	 * Method to verify that the minimum number of items have been selected such
	 * that the TireComparison page may be displayed.
	 */
	this.verifyMinimumSelected = function(){

		var numChecked = this.getNumberOfItemsSelected()

		//
		if( numChecked < MIN_ITEMS_FOR_COMPARE){
			alert(MIN_ERR_MSG);
			return false;
		}

		if( numChecked > MAX_ITEMS_FOR_COMPARE){
			alert(MAX_ERR_MSG);
			return false;
		}

		var cpns = this.getItemsSelectedCPNs()

		// do we need a call back?
		// Seam.Component.getInstance("tssBean").setSelectedCPNs( cpns );

		return true;
	}
}

function AddToCartHandler(){
	//MMYO Parameters for the add to cart link
	var MAKE_PARAM="&Make=";
	var MODEL_PARAM="&Model=";
	var YEAR_PARAM="&Year=";
	var OPTION_PARAM="&Option=";

	//Tire Parameters for the add to cart link
	var CPN_PARAM="&ItemNo=";
	var QTY_PARAM="&Quantity=";
	var LANG_PARAM="&lang=";

	var quantitySelectedId;

	this.setQuantitySelectedId = function(quantityId,replace){

		if( replace == null ){
			quantitySelectedId = quantityId;
			return ;
		}

		var l = quantityId.lastIndexOf(':');
		var t = quantityId.substring(0,(l + 1));
		quantitySelectedId = t + replace ;

	}

	var preAssembledLink;

	this.assembleRetailerLink = function(baseURL, cpnValue){

		var finalURL = baseURL + CPN_PARAM + encodeURIComponent( cpnValue ) +
					   QTY_PARAM + encodeURIComponent( document.getElementById(quantitySelectedId).value ) +
					   MAKE_PARAM + encodeURIComponent( document.getElementById('addToCartMake').value ) +
					   MODEL_PARAM + encodeURIComponent( document.getElementById('addToCartModel').value )+
					   YEAR_PARAM + encodeURIComponent( document.getElementById('addToCartYear').value ) +
					   OPTION_PARAM + encodeURIComponent( document.getElementById('addToCartOptions').value );

		preAssembledLink = finalURL;

	}

	this.executeRetailerLink = function(linkToExecute){

		if (linkToExecute != null){
			preAssembledLink = linkToExecute;
		}

		var url = encodeURI( preAssembledLink );

		window.location.href = url ;
	}


	this.assembleSizeRetailerLink = function(baseURL, cpnValue){

		var finalURL = baseURL +
		               CPN_PARAM    + encodeURIComponent( cpnValue ) +
					   QTY_PARAM    + encodeURIComponent( document.getElementById(quantitySelectedId).value ) +
					   MAKE_PARAM   + 'CUSTOM' +
					   MODEL_PARAM  + 'CUSTOM' +
					   YEAR_PARAM   + 'CUSTOM' +
					   OPTION_PARAM + 'CUSTOM' ;

		preAssembledLink = finalURL;

	}
}



/**
    This method is added to the onLoad event of each page.

	Set SEAM remoting and locale defaults.

	TODO - Change the locale functionality to use an input parameter
	       instead of ajax call.

           Create a MMYOComponent object within the Window Scope making
           it available to global javascript events.
*/
function initializePage() {

	// alert("Start intializePage()");
	var ele = document.getElementById('conversationId');
	if( ele ){
		var eleId = ele.value ;
		if( eleId ){
			Seam.Remoting.getContext().setConversationId( eleId );
			//alert ("MMYO.initializePage() - conversation id set to " + eleId);
		}
	}

	Seam.Remoting.displayLoadingMessage = function() {};
  	Seam.Remoting.hideLoadingMessage = function() {};
	Seam.Component.getInstance("localeBean").getLanguage(updateLocaleCallback);

	ymmoComponent = new YMMOComponent();
	ymmoComponent.init();
	addToCartHandler = new AddToCartHandler();
	localeComponent = new LocaleElement();
	if( !isResultsPage() ){
		highlightInitialTab();
	}

	/*
	var inp = document.getElementById('currentTireType');
	if( inp ){
		var currentTireType = inp.value ;
		if( currentTireType ){
			Seam.Component.getInstance("tssBean").setDisplayFitmentList(
				currentTireType,
				'en_US',
				tssCallbackHandler );
		}
	}
	*/

}


/** Allow for window.onload event to be chained.  Prevents like scripts from overwriting the onload event
*/
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
	} func();
	}
  }
}

/** Allow for window.onload event to be chained.  Prevents like scripts from overwriting the onload event
*/
function addUnloadEvent(func) {
  var oldonunload = window.onunload;
  if (typeof window.onunload != 'function') {
    window.onunload = func;
  } else {
    window.onunload = function() {
      if (oldonunload) {
        oldonunload();
	} func();
	}
  }
}

//Initialize base functionality for the page
addLoadEvent(initializePage);

// add unload hook for setting
if( isIE() ){
        addUnloadEvent(unloadPage);
}


/**
	A function to limit the entry to numerics only
*/
function checkNumber( e ) {

    var code;

    // a little browser work around
    if (!e) var e = window.event;
    if( e.charCode ){
    	code = e.charCode ;
    }
    else if (e.keyCode) {
    	code = e.keyCode;
   	}
    else if (e.which) {
    	code = e.which;
    }
    else {
    	code = 0;
    }

    if( code > 31
        && ( code < 48 || code > 57 ) ){
        return false ;
	}

    return true ;
}


function validateNumber( ele, min, max, msg ){

	if( isNaN( ele.value ) ){
		if( msg != null ){
			alert( msg );
		}
		ele.select();
		ele.focus();
		return false ;
	}

	var val = parseFloat( ele.value );
	if( val < min ){
		if( msg != null ){
			alert( msg );
		}
		ele.select();
		ele.focus();
		return false ;
	}

	if( val > max ){
		if( msg != null ){
			alert( msg );
		}
		ele.select();
		ele.focus();
		return false ;
	}

	return true ;
}


function validateQuantity( eleId, min, max, msg ){

	var l = eleId.lastIndexOf(':');
	var t = eleId.substring(0,(l + 1));
	var quantityId = t + 'quantity' ;
	var ele = document.getElementById( quantityId );

	var val = parseFloat( ele.value );
	if( isNaN( val ) ){
		if( msg != null ){
			alert( msg );
		}
		ele.select();
		ele.focus();
		return false ;
	}

	if( val < min ){
		if( msg != null ){
			alert( msg );
		}
		ele.select();
		ele.focus();
		return false ;
	}

	if( val > max ){
		if( msg != null ){
			alert( msg );
		}
		ele.select();
		ele.focus();
		return false ;
	}

	ele.value = val ;
	return true ;
}

// detect IE
function isIE(){
  var isThisIE  = ( navigator.appName == "Microsoft Internet Explorer" );
  return isThisIE ;
}


function unloadPage(){
        writeCIDCookie();
        return true ;
}


// helper function to write the current CID cookie
function writeCIDCookie(){
        var cid = Seam.Remoting.getContext().getConversationId();
        if( cid ) {
                // write a cookie
                document.cookie = "currentCID=" + encodeURIComponent(cid);
         }
}

// helper function to read the current cid cookie
function readCIDCookie(){
        var allcookies = document.cookie;
        // Look for the start of the cookie named "currentCID"
        var pos = allcookies.indexOf("currentCID=");

        // found it get the value
        if (pos != -1) {
            var start = pos + 11 ;
            var end = allcookies.indexOf(";", start);
            if (end == -1) end = allcookies.length;
            var value = allcookies.substring(start, end);
            value = decodeURIComponent(value);
			return value ;
        }
}

function clearCIDCookie(){
        document.cookie = "currentCID=" + "" ;
        // alert( document.cookie );

}


// simple function to detect a timeout condition and redirect to landing page
function tssCallbackHandler( result ){

	if( 'timeout' == result ){
		// error condition - redirect to landing page
		var h = window.location.host ;
		window.location.href = 'http://' + h + '/TSSapp/TireLanding.xhtml';
	}
}


function isResultsPage(){
	var found = document.getElementById( 'resultsTabs' )
 	if( found != null ){
 		return true ;
 	}
 	return false ;
}
