/** revision 1.1.2.34 **/
/******************** constants **********************/

var maxPhoneQuantity=nxVars.isCA?10:5;
var galleryURL="some URL here";
var rebateDataSets= new Hash();
var phoneRatingSets=new Hash();

//Image Swapping function

function swapImage(anchorObj, newImg) {

  var imgObj = $(anchorObj).$css('img.badge')[0];

  imgObj.src=newImg;

}

/******* tealeaf *************/

// if tealeaf

if (typeof(TeaLeaf)!='undefined'){
	if(window.TeaLeaf && TeaLeaf.Client && TeaLeaf.Client.Configuration){
		// add modal close ID to the TeaLeaf config
		TeaLeaf.Client.Configuration.tlSingleAttach.push({
			"domelementID": "detailsOverlayClose",    
			"domevent": "click",    
			"tlhandler": "TeaLeaf.Client.tlAddEvent"
		});
		TeaLeaf.Client.Configuration.tlSingleAttach.push({
			"domelementID": "galleryOverlayClose",    
			"domevent": "click",    
			"tlhandler": "TeaLeaf.Client.tlAddEvent"
		});	
	}
}




/******************** error messaging **********************/
var errBalloon=null;
var quantityErrMsg=new Hash({
	'en':'You have entered an invalid number of phones. Please specify between  1 and '+maxPhoneQuantity+' to continue.',
	'es':'Has ingresado una cantidad incorrecta de teléfonos. Por favor elige un número entre 1 y '+maxPhoneQuantity+' para continuar.'
});

var purchaseOptionErrMsg=new Hash({
	'en':'<strong>Choose a shopping path</strong><br>Please select \'Buy with new plan\' or \'Upgrade/Replace\' to continue. Click the links if you need more information.',
	'es':'<strong>Escoge una opción.</strong><br>Por favor selecciona \'Comprar con nuevo plan\' o \'Actualizar/Remplazar\' para continuar. Haz clic en las opciones para obtener más información.'
});

function validateQuantityField(fm){
	if(fm.phoneQuantity ){
		var v=parseInt(fm.phoneQuantity.value);
		if(isNaN(v)||v<1||v>maxPhoneQuantity){
			makeBalloon(quantityErrMsg);
			errBalloon.show();
			errBalloon.moveTo(getLeft(fm.phoneQuantity)-Math.round(getWidth(errBalloon.id)*0.95),getTop(fm.phoneQuantity)-getHeight(errBalloon.id));
			return false;
		}
	}
	return true;
}

function validatePurchaseType(fm){
	var stopFlow=false;
	if(fm.purchaseType)
	{
		var nd=new Collection(fm.purchaseType)
		var rVal=false;
		
		nd.forEach(function(v){
	           if(v.checked==true){
			   		if(v.value=='upgrade'){
						stopFlow=true;
						//If it is detail layer then detail layer will be closed before upgrade modal.
						if($('detailsOverlay')){
							detailsLayer.hide();
						}
						setTimeout(function(){
							upgradeFormSubmitHandler(null,fm,'/NASApp/onlinestore/Action/UpgradeNextPageAction');	
							//upgradeFormSubmitHandler(null,fm,'/upgrade_flow/login.php');						
						},0);
					}
					rVal=true;
	           }
	    });
		if(!rVal){
			makeBalloon(purchaseOptionErrMsg);
			errBalloon.show();
			errBalloon.moveTo(getLeft($(fm).$a('name','submission','input')[0])-Math.round(getWidth(errBalloon.id)*0.97),getTop($(fm).$a('name','submission','input')[0])-getHeight(errBalloon.id));
			stopFlow=true;
		}
	}
	return !stopFlow;
}

function makeBalloon(msg){
	var cont=errBal.template(msg);
	errBalloon=new widgets.dialog({id:'phoneErrorBalloon',className:'phoneModal',backingClass:'phoneModalBack',css:'position:absolute; z-index:2000; width:350'},true);
	//errBalloon=new widgets.dialog({id:'phoneErrorBalloon',css:'position:absolute; z-index:2000; width:350'});
	errBalloon.setContent(cont);	
	setOpacity(errBalloon.backer.id,0);
	errBalloon.show();
}

var errBal='<div class="errorBalloon balloon">'+
'	<div class="topCorner">'+
'		<div class="lCorner"><img src="/assets/images/shop/buk_ch_err_bal_tl.gif" alt="" /></div>'+
'		<div class="rCorner"><img src="/assets/images/shop/buk_ch_err_bal_tr.gif" alt="" /></div>'+
'		<div class="middle"><img src="/assets/images/spacer.gif" alt="" /></div>'+
'	</div>'+
'	<div class="outer">'+
'		<div class="inner">'+
'			<div class="contentContainer">'+
'				<div class="content"><a href="javascript:errBalloon.hide();"><img src="/assets/images/shop/icon_ch_err_close.gif" class="close" alt="" /></a>'+
'					<div class="textBlock">'+
'						<='+nxVars.lang+'=>'+
'					</div>'+
'				</div>	'+
'			</div>'+
'		</div>'+
'	</div>'+
'	<div class="bottomCorner">'+
'		<div class="lCorner"><img src="/assets/images/shop/buk_ch_err_bal_bl.gif" alt="" /></div>'+
'		<div class="rCorner"><img src="/assets/images/shop/buk_ch_err_bal_br.gif" alt="" /></div>'+
'		<div class="middle"><img src="/assets/images/shop/icon_checkout_err_arrow_right.gif" width="33" height="26" alt="" /></div>'+
'	</div>'+
'</div>';

/***************************** loadingMessage *****************************/
var loadingContent="";
loadingContent+='<div class="phonesModalContent">';
loadingContent+='<div id="loadingMessageContent">';
var lang_content = (nxVars.lang=='en')?'Loading, please wait...':'Espera un momento por favor...';
loadingContent+='<div class="content">'+lang_content+'<br /><img src="/assets/images/shop/checkout_trans_spin.gif" alt="'+lang_content+'"/></div>';
loadingContent+='</div>';
loadingContent+='</div>';
var loadingLayer=null;

function initLoading(){
	loadingLayer=new widgets.dialog({id:'loadingOverlay',className:'phoneModal',backingClass:'phoneModalBack',css:'position:absolute; z-index:500;'},true);
	loadingLayer.setContent(loadingContent);
	setOpacity(loadingLayer.backer.id,70);	
};

function showLoadingMessage(){
	if(!loadingLayer){
		initLoading();
	}
	loadingLayer.show();
	loadingLayer.center();	
}
function hideLoadingMessage(){
	loadingLayer.hide();
}

/**************************** initialize overlay layers *************************/
/*
Events.inQ((bis.ie&&bis.v==6)?'BodyLoad':'DOMLoad',function(){
	initLoading();
	initGallery();
	if(checkFunction("initDetails")){
		initDetails();
	}
});
*/


/************** gallery pop-up *************************/
var closeTxt=(nxVars.lang=='en')?'CLOSE':'CERRAR';
var galleryContent="";
galleryContent+='<div class="phonesModalContent">';
galleryContent+='	<div class="inner">';
galleryContent+='		<div class="aRight"><a href="#" class="actionBox" id="galleryOverlayClose">'+closeTxt+' X</a></div>';
galleryContent+='		<div id="phoneGalleryFlashContainer">';
// Hardcoded image file commented out to play the flash based on phone SKU
//galleryContent+='			<img src="/phone_proto/gallery_temp.gif" width="606" height="424" />';
galleryContent+='		</div>';
galleryContent+='	</div>';
galleryContent+='</div>';

var galleryLayer=null;

function initGallery(){
	galleryLayer=new widgets.dialog({id:'galleryOverlay',className:'phoneModal',backingClass:'phoneModalBack',css:'position:absolute; z-index:200;'},true);
	galleryLayer.setContent(galleryContent);
	setOpacity(galleryLayer.backer.id,70);	
	Events.add('galleryCloseClick','click',function(){galleryLayer.hide()});
	var closer=$('galleryOverlay').$c('actionBox','a')[0];
	Events.attach(closer,'galleryCloseClick',false,true,true);
};

function displayGallery(sku,gType, iHeight,iWidth,iTop,iLeft,detail, phonename){
	if(!galleryLayer){
		initGallery(sku,gType, phonename);
	}
	updateGallery(sku,gType,phonename);
	galleryLayer.show();
	var hi=getHeight('galleryOverlay');
	var top=iTop;
	var lft=iLeft;
	if(detail){
		lft=lft+iWidth/4;
	}
	else{
		top=iTop+iHeight/2-hi/2;
		lft=iLeft+iWidth/3;	
	}
	galleryLayer.moveTo(lft,top);
}


function updateGallery(sku,gtype, phonename){
// Call the load in phones_gallery.js to laod the flash and it's components
phoneGallery.load(sku,'phoneGalleryFlashContainer',gtype, phonename);
	//return ;
	// waiting on file/params for gallery flash
}

/******** rebate popup ************/
var closeTxt=(nxVars.lang=='en')?'CLOSE':'CERRAR';
var rebateContent="";
rebateContent+='<div class="phonesModalContent" style="width:405px">';
rebateContent+='	<div class="aRight"><a href="#" class="actionBox">'+closeTxt+' X</a>'+_Clearer+'</div>';
rebateContent+='	<div id="rebate-overlay">';
rebateContent+='	</div>';
rebateContent+='</div>';
var rebateWidget = null;
function initRebateOverlay(){
	var rw=rebateWidget;
	rw = new widgets.dialog({id:'rebateOverlay',className:'phoneModal',backingClass:'phoneModalBack',css:'position:absolute; z-index:500;'},true);
	rw.setContent(rebateContent);
	Events.add('rebatePopupCloseClick','click');
	Events.inQ('rebatePopupCloseClick',function(){rebateWidget.hide()});
	var closer=$(rw.id).$c('actionBox','a')[0];
	Events.attach(closer,'rebatePopupCloseClick',false,true,true);

	setOpacity(rw.backer.id,0);
	rebateWidget=rw;
}

function showPopulatedRebate(){
	if(!rebateWidget){
		initRebateOverlay();
		var elContent=document.$css('div.rebatepopup')[0];
		$('rebate-overlay').appendChild(elContent);
		//setDisplay(elContent,"block");
	}
	rebateWidget.show();
	var dim = getCenterDim($(rebateWidget.id));
	rebateWidget.moveTo(dim[0], dim[1]);
};

function getRebate(el,ptn,sku){
	waitingId=sku;
	if(!rebateDataSets[sku]){
		showLoadingMessage();
		XHR.quickSend({id:'phone-'+sku,url:el.getAttribute("url"),method:'GET',handler:setRebate,data:'phoneSKU='+sku+'&upgradePTN='+ptn});
	}else{
		waitingId="";
		displayRebate(rebateDataSets[sku],sku);
	}
};

function setRebate(data, target, rId){
	var pId=rId.split('-')[1];
	rebateDataSets[pId]=data.responseText;
	if(pId==waitingId){
		displayRebate(data.responseText+_Clearer,pId);
	}
	waitingId="";
};

function displayRebate(data, sku)
{
	if( !rebateWidget ){
		initRebateOverlay();
	}
	hideLoadingMessage();
	setHTML('rebate-overlay', data);
	rebateWidget.show();
	var dim = getCenterDim($(rebateWidget.id));
	rebateWidget.moveTo(dim[0], dim[1]);
	
};
function getCenterDim(el){
	var j=jutil;
	
	var w =getWidth(el);
	var h = getHeight(el);
	
	var t = j.scrollY()+(j.windowHeight()/2)-(h/2);
	
	if( t< 0) t=0;
	var l = j.scrollX()+(j.windowWidth()/2)-(w/2);
	if( l<0) l=0;
	
	return [l,t];
};


/****** Phone Detail *****/
Events.inQ('DOMLoad',function(){
	var a=$('phones-detail');
	if(a){
		phonedetail.showTransMessage(a,a.$a('name','phoneSKU','input')[0].value);
	}
});

var phonedetail = {

setup: function(quantityChg, styleChg,optChg,contractChg, activateChg){
	this.addStylChgCallback(styleChg);
	this.addOptChgCallback(optChg);
	this.addCntrctChgLstnrs(contractChg);
	this.addQtyChgLstnrs(quantityChg);
	this.addActivateChg(activateChg);
},

/**
 * Public interface to init the phone detail layer
 * @phoneSKU: the phoneSKU  for the current phone
 * @quantity: qunatity to be displayed in the quantity field
 * @upgrade:  indicate the purchage type 
 			  false/null/undefined: regular purchase
 			  true: upgrade option
 * @numOfMon: the default contact month - eg. 24, 12, 0
 * @activate: indicate whether to check the activate check box or not.
 			  false/null/undefined <=> unchecked
 			  true <=> checked
 */
 
initDt: 	function (rootelem, phoneSKU, quantity, upgrade, numOfMon, activate){
/*
	alert("phoneSKU="+phoneSKU+_NL
	+"quantity="+quantity+_NL
	+"upgrade="+upgrade+_NL
	+"numOfMon="+numOfMon+_NL
	+"activate="+activate);
*/	
	this.initStyles(rootelem, phoneSKU);
	this.setBackLink(rootelem);
	// init purchase option
	var opt;
	if( upgrade ){
		opt = rootelem.$css("input.id_upgopt")[0];
		if(opt)
			this.enableQtyCtrl(opt);
	}else if( upgrade == false){
		opt = rootelem.$css("input.id_selopt")[0];
	}
	if(opt){
		opt.checked =true;
		this.updateOpt(opt);	
	}
	//init quantity
	if(quantity){
		var q = this.qCtrl(rootelem);
		if(q){
			q.value = quantity;
		}
	}
	
	// init contract option
	var c=this.ctrctOptCtrl(rootelem);
	if(c){
		if(numOfMon ){
			//if the numOfMon is not null, init the default value for
			// the contract option.
			var opt =  c.$css("input[type=radio][value="+numOfMon+"]")[0];
			if( opt){
				opt.checked = true;
				this.dispCntractDt(opt);	
			}
		}else{
			//if the numOfMon is null, then open the current checked
			// contract option, and close others.
			var opt = c.$css("input[type=radio][checked]")[0];
			if( opt ){
				this.dispCntractDt(opt);	
			}
		}
	}
	
	// init activate check box	
	if(activate){
		var a = this.aCtrl(rootelem);
		if( a ){
			a.checked = activate;
		}
	}
	//Queue the Visual Voicemail behaviors for the upgrade layer
	if(typeof(vmbeh)!='undefined'){
		rootelem.runBehavior(vmbeh);
	}
	//Calling trans function call onload
	phonedetail.showTransMessage(rootelem,phoneSKU);
},

/**
 * Public: Adding callback method for the sytle change on the phone detail page
 * The callback method will take one argument phoneSKU as the following example:
 * 
 	function styleChanged( phoneSKU )
 */
addStylChgCallback: function( callback ){
	var ret = this.stylChgLstnrs.push(callback);						
},

/**
 * Public: Adding callback method for the purchase option changes.
 * The callback method will take two arguments 
 		@phoneSKU: the phone SKU number
 		@upgrade: true/false or undefined to indicate the option changed to.
   Exmample:
 		function purOptChanged( phoneSKU, upgrade){
 			if(upgrade ){
 				...
 			}else{
 				...
 			}
 		}
 *
 */
addOptChgCallback: function( callback){
	var ret = this.optChgLstnrs.push(callback);
},
/**
 * Public: Adding callback method for the contract option changes.
 * The callback method will take two arguments 
 		@phoneSKU: the phone SKU number
 		@numOfMon: the number of month of the contract: 0, 12, 24...
   Exmample:
 		function purOptChanged( phoneSKU, numOfMonth)
 *
 */
addCntrctChgLstnrs: function( callback){
	var ret = this.cntrctChgLstnrs.push(callback);
},

addQtyChgLstnrs: function( callback){
	this.qChgLstnrs.push(callback);
},

addActivateChg: function( callback){
	this.activateChtLstnrs.push(callback);
},

/**
 * Private: init style dropdown list by the current phone id
 */
initStyles:	function (rootelem, phoneSKU){
	var colorSelector = this.styleCtrl(rootelem);
	
	if( colorSelector ){
		var options =colorSelector.options;
		for(var i = 0; i < options.length; i++){
			if (options[i].value ==  phoneSKU ){
				colorSelector.selectedIndex = i;
				this.onStylChg(colorSelector, true);
				break;
			}
		}
	}
},

setBackLink: function(rootelem){
	Events.attach($(rootelem).$css("a.id_tolist"),'detailsCloseClick',false,true,false);
},

/**
 * Update elements regarding the out-of-stock status
 * of stock status when the 
 * current phone is changed
 */
updateOOS:	function (rootelem, isOutOfStock){

	var rootelem = $(rootelem);
	var elems = rootelem.$css(".disable-oos");
	
	if(isOutOfStock=="true"){
		jutil.display(rootelem.$css(".d-outofstock"));
		jutil.suppress(rootelem.$css(".h-outofstock"));
		elems.forEach(function(elem){
			phonedetail.beforeDisabled(elem);
			elem.disabled =true;
		});
	}else{
		jutil.suppress(rootelem.$css(".d-outofstock"));
		jutil.display(rootelem.$css(".h-outofstock"));
		elems.forEach(function(elem){
			elem.disabled =false;
			phonedetail.afterEnabled(elem);
		});
	}
},

beforeDisabled: function(el){
	if(el.nodeName=="INPUT" &&
		el.type== "image" &&
		el.name=="submission"){
		var imgsrc = this.getSelImgSrc(el, "DISABLED");
		el.src=imgsrc;
	}
},

afterEnabled: function(el){
	if(el.nodeName=="INPUT" &&
		el.type== "image" &&
		el.name=="submission"){
		var imgsrc = this.getSelImgSrc(el, "ENABLED");
		el.src=imgsrc;
	}
},

getSelImgSrc: function(el, nodename){
	var nodename =nodename.toUpperCase();
	var xml = $(el).$anc('div.quantitySet').$css("xml[name=imgsrc]")[0];
	var e = jutil.first(jutil.first(xml));
	do{
		if( e.nodeName.toUpperCase() == nodename){
			break;
		}
		e = jutil.next(e);
	}while( e );
	return e.firstChild.nodeValue;
},
/**
 * update element according to the current selected style from control
 */
onStylChg:	function (control, nolistner){
	var selPhoneId = control.options[control.selectedIndex].value;
	// set image
	var detailBody = this.detailRoot(control);
	
	detailBody.$css("img.id_phone-image")[0].src=this.getValue(selPhoneId, "image");
	var gallery = this.getValue(selPhoneId,"gallery");
	if(gallery=='true'){
		jutil.display(detailBody.$css("div.id_360view")[0]);
	}else{
		jutil.suppress(detailBody.$css("div.id_360view")[0]);
	}

	detailBody.$css("input.id_phoneSKU")[0].value=selPhoneId;
	detailBody.$css("input.id_phone-emid")[0].value=this.getValue(selPhoneId,"emids");
	
	setHTML(detailBody.$css("p.id_intro-promo")[0],
				this.getValue(selPhoneId,"desc"));		
				
	setHTML(detailBody.$css("p.id_promoDetail")[0],
				this.getValue(selPhoneId,"promo"));
				
	setHTML(detailBody.$css("h1.id_phoneheader")[0],
				this.getValue(selPhoneId,"header"));

	//hide/show relative components
	this.updateOOS(detailBody, 
					this.getValue(selPhoneId, "is-out-stock"));
	if(!nolistner){
		this.stylChgLstnrs.forEach(function(func,i){
				func.call(this,selPhoneId);
			});
	}
	//Transactional message function call
	phonedetail.showTransMessage(detailBody,selPhoneId);
					
},

//Transactional message function
showTransMessage: function (detailBody,selPhoneId){
	var control=detailBody.$t('select');
	if(control.length==0){return;}
	control=control[0];
	var deviceMessage = control.options[control.selectedIndex].getAttribute("deviceMessage");
	deviceMessage = deviceMessage == 'true'?true:false;
	if(deviceMessage)
	{
		detailBody.$c('deviceMessage').toggleOff();
		detailBody.$('deviceMessage-'+selPhoneId).toggleOn();
		detailBody.$c('qtyPurchaseSelect').toggleOff();
	}
	else
	{
		detailBody.$c('deviceMessage').toggleOff();
		detailBody.$c('qtyPurchaseSelect').toggleOn();
	}
},

getValue:	function (objName, key){
	var p=$("phonestyles-"+objName);
	var c = jutil.first(p);
	do{
		if( c.getAttribute('name') == key){
			break;
		}
		c = jutil.next(c);
	}while( c );
	return c.getAttribute("value");
	//return $("phonestyles-"+objName).$css("param[name="+key+"]")[0].getAttribute("value");
},
/** looking for the detail content containder. All the elements for the detail
 * has to be containded and searched inside of this container.
 *  @elem: root element
 */ 
detailRoot:	function (elem){
	return $(elem).$anc('div.phone-detail-content');
},

styleCtrl:	function (rootelem){
	if( !rootelem)
		rootelem = document;
	
	return $(rootelem).$css("select.id_phoneColor")[0];
},

ctrctOptCtrl: function(rootelem){
	if(!rootelem)
		rootelem = document;
		
	return $(rootelem).
			$css("div.id_upgrade-price")[0];
},

qCtrl: function (rootel){
	if(!rootel)
		rootel = document;
	return $(rootel).
			$css("input[type=text][name=phoneQuantity]")[0];
},

aCtrl: function( rootel){
	if(!rootel)
		rootel = document;
	return $(rootel).
			$css("input[type=checkbox][name=isUpgradeNow]")[0];
},

getCurSKU:	function (rootelem){
	if(!rootelem)
		rootelem = document;
	return $(rootelem).$css("input.id_phoneSKU")[0].value;
},

showGallery:	function (ctrl){
	var detailBody = this.detailRoot(ctrl);
	var img=detailBody.$css("img.id_phone-image")[0];
	var phoneName= getHTML(detailBody.$css("h1.id_phoneheader")[0]);
	
	var iHgt=getHeight(img);
	var iTop=getTop(img);
	var iLft=getLeft(img);
	var iWid=getWidth(img);
/*
	alert("Under construction."+_NL+
		"SKU="+this.getCurSKU(detailBody)+_NL+
		"Type="+ctrl.name+_NL+
		"Phone Name="+phoneName);
	*/	
	displayGallery(this.getCurSKU(detailBody),ctrl.name, iHgt,iWid,iTop,iLft,true, phoneName);	
	/********************************Omniture Code*************************************/
	s_linkTrackVars='prop8';
	s_linkType='o';
	s_prop8='360 View: '+this.getCurSKU(detailBody);
	s_lnk=s_co(this);
	s_gs('sprintglobal');
	return false;
},



/** ** ** ** ** ONLY for New Phone Selction Detail *** *** **/
updateOpt: function(curOpt )
{
	this.detailRoot(curOpt).$css('form.id_selectaction')[0].action= curOpt.value;
},

enableQtyCtrl: function(opt){
	var optCtrl = this.qCtrl(this.detailRoot(opt));
	if(this.isUpgrade(opt)){
		optCtrl.disabled=true;
		removeClass(optCtrl, "disable-oos"); //remove from the out-of-stock actions
	}else{
		optCtrl.disabled=false;
		addClass(optCtrl, "disable-oos");
	}
},

isOptChg: function(curOpt){
	var a= this.detailRoot(curOpt).$css('form.id_selectaction')[0].action;
	var v = curOpt.value;
	return !a.endsWith(v);
},

isUpgrade: function(opt){
	return ( hasClass(opt, "id_upgopt"));
},

onOptClick: function(opt ){
	if(this.isOptChg(opt)){
		this.onOptChg(opt);		
	}
},

onOptChg:	function (opt){
	this.updateOpt(opt);
	this.enableQtyCtrl(opt);
	if(this.optChgLstnrs.length > 0){
		var curPhoneSKU = this.getCurSKU(this.detailRoot(opt));
		var upgrade = false;

		if( this.isUpgrade(opt))
			upgrade = true;
			
		this.optChgLstnrs.forEach(function(func){
				func.call(this,curPhoneSKU, upgrade);
		});	
	}
},
onQChg: function(ctrl){
	if( this.qChgLstnrs.length >0){
		var curPhoneSKU = this.getCurSKU(this.detailRoot(ctrl));
		
		this.qChgLstnrs.forEach(function(func){
			func.call(this, curPhoneSKU, ctrl.value );
		});
	}
},
onActivateChg: function(ctl){
	if(this.activateChtLstnrs.length>0){
		var curPhoneSKU = this.getCurSKU(this.detailRoot(opt));
		
		this.activateChtLstnrs.forEach(function(func){
			func.call(this, curPhoneSKU, ctrl.checked );
		});
	}
},
//this is callback method from select phone detail page.
//It is used to check if the qunatity input is valide to 
// determine if allow user to continue to submit
onSelSubmit: function(fm){
	if(validatePurchaseType(fm))
	{
		var qCtrl = this.qCtrl(this.detailRoot(fm));
		if(qCtrl && !qCtrl.disabled ){
			return validateQuantityField(fm);
		}
	}else{
		return false;
	}
},

/** ** ** ** ** ONLY for Upgrade Phone Detail *** *** **/
isCntractOptChg: function( curOpt ){
	var selOpt =  $(curOpt).$anc('div.priceOption');
	if(!jutil.isSuppressed(selOpt.$css(".priceDetail"))){ // alread expandded
		return false;			
	}
	return true;
},

dispCntractDt: function( curOpt ){
	var upgradePriceBody = this.ctrctOptCtrl(this.detailRoot(curOpt));
		
	var opts = upgradePriceBody.$css('div.priceOption');
	var selOpt =  $(curOpt).$anc('div.priceOption');
	
	opts.forEach(function(optC){
		if(optC != selOpt ){
			jutil.suppress(optC.$css(".priceDetail")); // close all the price details
			jutil.display(optC.$css(".yourprice"));
		}else{
			jutil.display(optC.$css(".priceDetail")); // close all the price details
			jutil.suppress(optC.$css(".yourprice"));
		}
	});
},

onCntrctClick: function(opt){
	if( this.isCntractOptChg (opt)){
		this.onCntrctChg(opt);
	}
},

onCntrctChg:	function (opt){
	this.dispCntractDt( opt );
	
	// callback check
	if(this.cntrctChgLstnrs.length >0){
		var curPhoneSKU = this.getCurSKU(this.detailRoot(opt));
		var numOfMon = opt.getAttribute("value");
		
		this.cntrctChgLstnrs.forEach(function(func){
				func.call(this,curPhoneSKU, numOfMon);
		});
	}
},

onActivateChg: function(opt){
	if(this.activateChtLstnrs.length >0){
		var curPhoneSKU = this.getCurSKU(this.detailRoot(opt));
		
		this.activateChtLstnrs.forEach(function(func){
				func.call(this,curPhoneSKU, opt.checked);
		});
	}
},

stylChgLstnrs: new Array(),
optChgLstnrs: new Array(),
cntrctChgLstnrs:new Array(),
qChgLstnrs: new Array(),
activateChtLstnrs: new Array()
};

var jutil = {
	
display: function(name){
	if( name ){
		var obj = $(name);
		
		if(!isArray(obj) && !isCollection(obj)){
			obj=[obj];
		}
		
		obj.forEach(function(elem){
			elem.style.display=elem.$oldDisplay ||'';
		});
	}
},

isSuppressed: function (name){
	if( name ){
		var obj = $(name);
		
		if(!isArray(obj) && !isCollection(obj)){
			obj=[obj];
		}
		
		obj.forEach(function(elem){
			var curDisp = getStyle(elem, 'display');
			
			if( curDisp != 'none' ){
				return false;
			}
		});
		return true;
	}
},

suppress: function (name){
	if( name ){
		var obj = $(name);
		
		if(!isArray(obj) && !isCollection(obj) ){
			obj=[obj];
		}
		
		obj.forEach(function(elem){
			var curDisp = getStyle(elem, 'display');
			
			if( curDisp != 'none' ){
				elem.$oldDisplay=curDisp;
			}
			elem.style.display='none';
		});
	}
},
//get the viewport left position
scrollX: function(){
	//for IE 6
	var de = document.documentElement;
	
	return self.pageXOffset ||
		(de && de.scrollLeft) ||
		document.body.scrollLeft;
},
scrollY: function(){
	//for IE 6
	var de = document.documentElement;
	return self.pageYOffset ||
		(de && de.scrollTop) ||
		document.body.scrollTop;
},
// size of the viewport
windowHeight: function(){
	var de = document.documentElement;
	return self.innerHeight ||
		(de && de.clientHeight )||
		document.body.clientHeight;
},
windowWidth: function(){
	var de = document.documentElement;
	return self.innerWidth ||
		(de && de.clientWidth )||
		document.body.clientWidth;
},
first: function(el){
	el= el.firstChild;
	return el && el.nodeType !=1 ? this.next(el):el;
},
next: function(el){
	do{
		el=el.nextSibling;
	}while( el && el.nodeType!=1);
	return el;
}
};
//Added this dummy function to call the showGallery method from the phonedetail
function showGallery(ctrl){
	phonedetail.showGallery(ctrl);
}
//CNET Rating function

function detailCNETRatings(sku,el){
	var pId=sku+'CNET';
	var mId=pId;
	if(!phoneRatingSets[mId]){				
		var obj={
			id:mId,
			message:ratingsLoadMessage,
			close:ratingsCloseText
		}
		var u = el.getAttribute('href');
		phoneRatingSets[mId]=new widgets.dialog({id:mId+'-RatingsOverlay',className:'phoneNonModal',backingClass:'phoneNonModal',css:'position:absolute; z-index:600;',autoClose:true});
		phoneRatingSets[mId].setContent(ratingsCNETTemplate.template(obj));
		phoneRatingSets[mId].show();
		phoneRatingSets[mId].moveTo(getLeft(el)+getWidth(el),getTop(el)+getHeight(el));
		Events.attach($css('#'+mId+'-RatingsOverlay a.actionBox')[0],'ratingsCloseClick',false,true,true);				
		XHR.quickSend({id:'ratings-'+mId,url:u,method:'GET',target:mId+'-rating-content', handler:setDetailRatingContent});
	}		
	else{
		phoneRatingSets[mId].moveTo(getLeft(el)+getWidth(el),getTop(el)+getHeight(el));
		phoneRatingSets[mId].show();
	}
	return false;
}
		
function setDetailRatingContent(content, target,rid) {
	setHTML(target,content.responseText);
	Behaviors.run(phoneDetailLinkBehavior,$(target));
	XHR.deleteRequest(rid);
	content=null;
}

var ratingsLoadMessage=(nxVars.lang=='en')?'Loading....':'Espera un momento por favor...';
var ratingsCloseText=(nxVars.lang=='en')?'CLOSE':'CERRAR';
var ratingsTemplate='<div class="ratingsLayer overlay" id="<=id=>-rating-overlay">'
+'<div class="outer">'
+'<div class="aRight"><a href="#" class="actionBox"><=close=> X</a></div>'
+'<div class="content" id="<=id=>-rating-content">'
+'<=message=>'
+'</div>'
+'</div>'
+'</div>';
var ratingsCNETTemplate='<div class="cnetRatingsLayer overlay" id="<=id=>-rating-overlay">'
+'<div class="outer">'
+'<div class="aRight"><a href="#" class="actionBox"><=close=> X</a></div>'
+'<div class="content" id="<=id=>-rating-content">'
+'<=message=>'
+'</div>'
+'</div>'
+'</div>';

function hideRatings(e,el){
	phoneRatingSets[$(el).$anc('div.overlay').id.split('-')[0]].hide();
}
Events.add('ratingsCloseClick','click',hideRatings);

//Dynamically building bazaar voice read review URL

function baseBVUrl(){
	var protocal=nxVars.secure?'https://':'http://';
	var subDomain='reviews.nextel.com/';
	var environment='';
	if(nxVars.isProd){
		environment='5611a/';
	} else {
		environment='bvstaging/5611/';
	}
	var groupId=$css('div.phone-detail-content')[0].getAttribute('groupid');
	return protocal+subDomain+environment+groupId
}
function readReviewBVUrl(){
	return baseBVUrl()+'/reviews.htm?format=embedded';
}

//Dynamically building bazaar voice write a review URL
function writeReviewBVUrl(){
	return baseBVUrl()+'/submitreview.htm?format=embedded&user=__USERID__';
}

function ratingsDisplayed(totalReviewsCount, avgRating, ratingsOnlyReviewCount, recommendPercentage, productID)
{
    if (totalReviewsCount > 0) {
        var bvRevCntr = document.getElementById("BVReviewsContainer");
        if (bvRevCntr) { bvRevCntr.style.display = "block"; }
    }
    // Other custom items leveraging these values.
    // Added the following line per the omniture request
	if (typeof(Analytics.eComStore)!='undefined'){
		//Commented out the following code because omniture is not enabled
		Analytics.eComStore.setDetailPageRatingsHandlers();
	}
}
//Omniture reporting function

function pageChanged(pageName,pageStatus){
	if(pageName == 'ThankYou' && pageStatus == 'REVIEW_THANKYOU'){
		if (typeof(Analytics.eComStore)!='undefined'){
			Analytics.eComStore.ratingsReviewCompleteHandler();
		}
    }
}

var BVisLoaded = false;  
function BVcheckLoadState() {  
	 if(!BVisLoaded) {  
		 var page = document.getElementById('BVFrame').src;  
		//document.getElementById('BVFrame').src='http://reviews.nextel.com/bvstaging/logging?page=' + escape(page);  
		 //document.getElementById('BVFrame').src='http://reviews.nextel.com/logging?page=' + escape(page);  
		 document.getElementById('BVFrame').src=(nxVars.isProd)?'http://reviews.nextel.com/logging?page=':'http://reviews.nextel.com/bvstaging/logging?page='+ escape(page);
		 document.getElementById('BVReviewsContainer').innerHTML = 'Oops, we\'ve run into a problem. Please go back and try again';  
	}  
}  
 
function bvLoadRR() {  
	 var bvPage=readReviewBVUrl();
	// var bvPage = 'http://reviews.nextel.com/bvstaging/5611/test0/reviews.htm?format=embedded';  
	 var bvReviewIDName = 'featurereview';  
	   
	 var bvReviewIDRegex = new RegExp('[?&]' + bvReviewIDName + '=([^&#]+)');  
	 var bvReviewIDMatch = bvReviewIDRegex.exec(window.location.search);  
	 var bvReviewID = bvReviewIDMatch ? decodeURIComponent(bvReviewIDMatch[1]) : null;  
	   
	 document.getElementById('BVFrame').src = /^[0-9]+$/.test(bvReviewID) ? bvPage + '&reviewid=' + bvReviewID : bvPage;  
	   
	 //Timeout for review load.  Consider reviews unavailable if not loaded within 15 seconds  
	 setTimeout("BVcheckLoadState()", 15000);  
}  

if(typeof(BVisLoaded) == 'undefined') {
	var BVisLoaded = false;
}
function BVsubmissionCheckLoadState(bvErrorMsg){
	if(!BVisLoaded){
		document.getElementById('BVSubmissionFrame').src="";
		// If the content was not pushed, show a friendly message
		document.getElementById('BVSubmissionContainer').innerHTML = bvErrorMsg;
	}
}

function bvLoadRRFeedbackYesSubmission(reviewId){
    bvLoadRRSubmissionPage(baseBVUrl()+'/review/' + reviewId + '/submitpositive.htm?format=embedded&user=__USERID__');
	if((typeof(executeWriteReview)!='undefined') && (executeWriteReview!=null)){
		executeWriteReview=false;
		sprintOpenWriteRating();
		executeWriteReview=true;
	} else {
		sprintOpenWriteRating();
	}
}

function bvLoadRRFeedbackNoSubmission(reviewId){
    bvLoadRRSubmissionPage(baseBVUrl()+'/review/' + reviewId + '/submitnegative.htm?format=embedded&user=__USERID__');
	if((typeof(executeWriteReview)!='undefined') && (executeWriteReview!=null)){
		executeWriteReview=false;
		sprintOpenWriteRating();
		executeWriteReview=true;
	} else {
		sprintOpenWriteRating();
	}
}

function bvLoadRRInappropriateSubmission(reviewId){
    bvLoadRRSubmissionPage(baseBVUrl()+'/review/' + reviewId + '/submitinappropriate.htm?format=embedded&user=__USERID__');
	if((typeof(executeWriteReview)!='undefined') && (executeWriteReview!=null)){
		executeWriteReview=false;
		sprintOpenWriteRating();
		executeWriteReview=true;
	} else {
		sprintOpenWriteRating();
	}
}

function bvLoadRRSubmissionPage(bvPage) {
    var bvoice_user = ""; // Populate with user authentication string for non-anonymous
    var bvErrorMsg = 'Review Submission Currently Unavailable';
    var bvPageMatch = /[?&]bvpage=([^&#]+)/.exec(window.location.search);
    var bvRegex = new RegExp('^' + window.location.protocol + '\/\/([A-Za-z0-9-.]+[.])?' + document.domain + '\/');
    if(bvPage && bvRegex.test(bvPage)) {
		BVisLoaded = false;
		document.getElementById('BVSubmissionFrame').src = bvPage.replace(/__USERID__/, bvoice_user);
		setTimeout("BVsubmissionCheckLoadState(\"" + bvErrorMsg + "\")", 15000);
    } else {
		document.getElementById('BVSubmissionContainer').innerHTML = bvErrorMsg;
    }
}

function bvLoadRRSubmission() {
	var bvoice_user = ""; // Populate with user authentication string for non-anonymous
	var bvErrorMsg = 'Review Submission Currently Unavailable';
	var bvPageMatch = /[?&]bvpage=([^&#]+)/.exec(window.location.search);
	// var bvPage = bvPageMatch ? decodeURIComponent(bvPageMatch[1]) : null;
	var bvPage = writeReviewBVUrl();
	var bvRegex = new RegExp('^' + window.location.protocol + '\/\/([A-Za-z0-9-.]+[.])?' + document.domain + '\/');
	
	if(bvPage && bvRegex.test(bvPage)) {
		BVisLoaded = false;
		document.getElementById('BVSubmissionFrame').src = bvPage.replace(/__USERID__/, bvoice_user);
		setTimeout("BVsubmissionCheckLoadState(\"" + bvErrorMsg + "\")", 15000);
	} else {
		document.getElementById('BVSubmissionContainer').innerHTML = bvErrorMsg;
	}
}

function sprintOpenRating(){
	Events.send('tabOn','tab-ratings');
	return false;
}

function sprintOpenWriteRating(){
	Events.send('tabOn','tab-write-ratings');
	return false;
}

function sprintMoveModalToTop(){
	if(typeof(setDefaultTab)!='undefined'){
		if(isValidText(setDefaultTab)){
			window.scroll(0,getTop(setDefaultTab));
		} else {
			if ($('tab-write-ratings')){
				if ($('tab-write-ratings').hasClass('on')){
					window.scroll(0,getTop('tab-write-ratings'));
				}
			} else if($('tab-ratings')){
				   		if($('tab-ratings').hasClass('on')){
							window.scroll(0,getTop('tab-ratings'));
						}
			}
		}
	}
}

function sprintReviewCompleted(){
	if($('detailsOverlay')){
		detailsLayer.hide();
	}
}

function sprintDisplayReviewRatings(){
	sprintOpenRating();
   	setTimeout(function(){$('BVFrame').src="";bvLoadRR();},1);
}