

// *** START SEARCH WITHIN ***
function showSearchWithin() {
	//document.frmWithinSearch.txtSearchWithin.value = " type search text here ";
	var SearchWithinForm = $('frmSearchWithin');
	Effect.Appear(SearchWithinForm);
	//document.frmWithinSearch.txtSearchWithin.focus();
}
// *** END SEARCH WITHIN ***

var __SUBMITTEDALREADY = false;
function PostbackOnEnterKeyOnce(e,validgrp,name){
	var keypress = window.event ? e.keyCode : e.which;
	if(keypress!=13) {
		return;
	}
	if(validgrp!='') {
		VAM_ValOnClick(validgrp);
		if (VAM_ValOnSubWGrp(validgrp,'')) 	{
			if(__SUBMITTEDALREADY)
				return;
			__SUBMITTEDALREADY = true;
			__doPostBack(name,'');
		}
	}
	else {
		if(__SUBMITTEDALREADY)
			return;
		__SUBMITTEDALREADY = true;
		__doPostBack(name,'');
	}
}

// *** function to trigger postback event on enter key press ***/
function PostbackOnEnterKey(e,validgrp,name) {
	var keypress = window.event ? e.keyCode : e.which;
	if(keypress!=13) { return; }
	if(validgrp!=='') {
		VAM_ValOnClick(validgrp);
		if (VAM_ValOnSubWGrp(validgrp,'')) 	{
			__doPostBack(name,'');
		}
	} else {
		__doPostBack(name,'');
	}
}

function AJAXValidEmailDomain() { 
	var field = $('TxtEmail');
	if(field == null)
		field = $('txtEmail');
	
	var eValue = field.value;

	//only checking email domain, when there are no VAM errors shown
	if ($('valEmailValid') != null && $('valEmailValid').getStyle('visibility') == 'hidden' && eValue.length > 0)
	{
		new Ajax.Request(baseUrl + "AJAXLoginRegistration.aspx", 
		{
			onSuccess : function(resp) {DisplayResultsFromDomainCheck(resp);},
			parameters : { EmailAddress :  eValue }
		});
	}
}

function DisplayResultsFromDomainCheck(resp) {
	if (resp.responseText.length > 0) 
	{	
		if (resp.responseText == 'False')
		{	
			var obj = $('valEmailValid');
			var objEmail = $('TxtEmail');
			if(objEmail == null)
				objEmail = $('txtEmail');

			var strDomain = objEmail.value.split('@');
			obj.show();
			obj.setStyle({visibility: 'visible'});			
			obj.innerHTML = "<br>please check that " + strDomain[0] + "@" + strDomain[1].toUpperCase() + " is correct before continuing";
			objEmail.addClassName('wrong'); //show red border around email address
		}
		else
		{
			var objEmail = $('TxtEmail');
			if(objEmail == null)
				objEmail = $('txtEmail');
			objEmail.removeClassName('wrong');
		}
	}
}



// *** ADD TO WANT LIST ***
var STIDToAddToWant='';
var glbAllowRedirect = true;

function AddToWantList(obj,UserStatus, allowRedirect) {
	var redirect = true;
	if(allowRedirect != undefined){
		redirect = allowRedirect;
		glbAllowRedirect = allowRedirect;
	}
	
	var STID = '';
	if (typeof(obj)=="string") {
		if (obj.indexOf("rollover_hyplnkAddToWant_") > -1) {  //we are coming from AJAX rollover
			STID = obj.replace("rollover_hyplnkAddToWant_","");
			objGlobal = $("hyplnkAddToWant");
		}
	} else {
		objGlobal = obj; // no 'var' so this is a global variable
		var objID = obj.id;
		//find the ID of the title hyperlink
		objID = objID.substring(0, objID.indexOf("hyplnkAddToWant")) + "hyplnkItemName1";
		//if image does not have href then (this happens in UcItemDetail)
		if($(objID).href=='') {
			objID = obj.id;
			//search for hyplnkAddToTradeList control for getting href
			objID = objID.substring(0, objID.indexOf("hyplnkAddToWant")) + 'hyplnkAddToTradeList';
		}
		var objHyperLink = $(objID);
		
		//some urls are pretty some or not so parse STID accordingly
		if(objHyperLink.href.indexOf(".aspx") > -1){
			STID = objHyperLink.href.substr(objHyperLink.href.indexOf("=") + 1);
		} else {
			STID = objHyperLink.href.substr(objHyperLink.href.lastIndexOf("/", objHyperLink.href.length - 2) + 1).replace("/", "");
		}
	}

	if (objGlobal!==null) Element.update(objGlobal,"&nbsp;");  //hide the "add to want" until the response comes back

	var pars = 'STID=' + STID + '&redirect=' + ((redirect)?'1':'0') + '&cb=' + Math.random();

	if (UserStatus=='g') {	
		obj.href = baseUrl + "WebFrmAddToWant.aspx?STID=" + STID;
		document.location.href = baseUrl + "WebFrmAddToWant.aspx?STID=" + STID;
	} else {
		STIDToAddToWant=STID;
		var myAjax = new Ajax.Request(baseUrl + 'AJAXAddToWant.aspx', { method: 'get', parameters: pars, onSuccess: showResponse });
		//return false;	
	}
}

function AddToWantListIcon(obj,UserStatus, STID) {
	objGlobal = obj; // no 'var' so this is a global variable
	
	if (objGlobal!==null) Element.update(objGlobal,"&nbsp;");  //hide the "add to want" until the response comes back

	var pars = 'STID=' + STID + '&cb=' + Math.random();

	if (UserStatus=='g') {	
		obj.href = baseUrl + "WebFrmAddToWant.aspx?STID=" + STID;
		document.location.href = baseUrl + "WebFrmAddToWant.aspx?STID=" + STID;
	} else {
		STIDToAddToWant=STID;
		var myAjax = new Ajax.Request(baseUrl + 'AJAXAddToWant.aspx', { method: 'get', parameters: pars, onSuccess: showResponseIcon });
		//return false;	
	}
}

function AddToWantList2(obj, stid){
	objGlobal = obj; // no 'var' so this is a global variable
	if (objGlobal!=null) Element.hide(objGlobal);  //hide the "add to want" until the response comes back
	
	var pars = 'STID=' + stid + '&cb=' + Math.random();

	STIDToAddToWant=stid;
	var myAjax = new Ajax.Request(baseUrl + 'AJAXAddToWant.aspx', { method: 'get', parameters: pars, onSuccess: showResponse });
}

function showResponse(resp) {
	if (resp.responseText == "1") {
		//moveToWantList();  //to animate, uncomment this
		Element.update(objGlobal, "added to<br>want list");
		objGlobal.addClassName("added");
		Element.show(objGlobal);
		//new Effect.Grow(objGlobal, {duration :2.5, queue:'end'});
		//new Effect.Appear(objGlobal, {duration:1, queue:'end'}); 
		new Effect.Pulsate(objGlobal, {duration: 4.0, pulses: 2.0, queue:'end'});
		
		// if the want list is empty then hide the message in the TopHeaderMenu
		var objPageAlert = $("ucTopHeaderMenu_divRightUserAlert");
		if (objPageAlert) {
			if (objPageAlert.innerHTML.indexOf("list is empty",0)>-1){
				objPageAlert.hide();
			}
		};		
	} else if(resp.responseText == "2") {
		Element.update(objGlobal, "item already<br>on want list");
		objGlobal.addClassName("added");
		Element.show(objGlobal);
		new Effect.Pulsate(objGlobal, {duration: 4.0, pulses: 2.0, queue:'end'});		
	}
	else if(resp.responseText=="-1") {
		var link = baseUrl + "WebFrmAddToWant.aspx?STID=" + STIDToAddToWant;
		objGlobal.href = link;
		
		if(glbAllowRedirect){
			document.location.href = link + "&firstWant=1";
		} else {
			parent.document.location.href = link + "&firstWant=1";
		}
	} else	{
		//there was a problem, so just redirect the browser to AddToWant
		if(glbAllowRedirect){
			document.location.href = resp.responseText;
		} else {
			parent.document.location.href = resp.responseText;
		}
		objGlobal.href = resp.responseText;
	}
}
function showResponseIcon(resp) {
	var AJAXResponse = resp.responseText;
	if (resp.responseText == "1") {
		//moveToWantList();  //to animate, uncomment this
		Element.update(objGlobal, "<img src='/images/icon-want-it-check.gif'>w");
		objGlobal.removeClassName("wantW");
		objGlobal.addClassName("wantWadded");
		objGlobal.writeAttribute("title", "item has been added to your want list");
		Element.show(objGlobal);
		new Effect.Pulsate(objGlobal, {duration: 3.0, pulses: 2.0, queue:'end'});
		
		// if the want list is empty then hide the message in the TopHeaderMenu
		var objPageAlert = $("ucTopHeaderMenu_divRightUserAlert");
		if (objPageAlert) {
			if (objPageAlert.innerHTML.indexOf("list is empty",0)>-1){
				objPageAlert.hide();
			}
		};
		
	} else if(resp.responseText == "2") {
		Element.update(objGlobal, "<img src='/images/icon-want-it-check.gif'>w");
		objGlobal.removeClassName("wantW");
		objGlobal.addClassName("wantWadded");
		objGlobal.writeAttribute("title", "item already on your want list");
		Element.show(objGlobal);
		new Effect.Pulsate(objGlobal, {duration: 3.0, pulses: 2.0, queue:'end'});		
	}
	else if(resp.responseText=="-1") {
		objGlobal.href = baseUrl + "WebFrmAddToWant.aspx?STID=" + STIDToAddToWant;
		document.location.href = baseUrl + "WebFrmAddToWant.aspx?STID=" + STIDToAddToWant + "&firstWant=1";
	} else	{
		//there was a problem, so just redirect the browser to AddToWant
		document.location.href = AJAXResponse;
		objGlobal.href = AJAXResponse;
	}
}
//*** END ADD TO WANT LIST ***

function ShowRejectTradeWarning(obj){
  var index = 0;
   
  if (document.getElementById(obj.id + '_1').checked == true) {
        index=1;
      }
  if (document.getElementById(obj.id + '_3').checked == true) {
        index=3;
      }
   
     switch(index) {
		case 1:
		   $('divMainText').show();
		   $('divSendItemWorthMore').show();
		   $('divNoLongerWantItem').hide();
		   break;
		case 3:
		   $('divMainText').show();
		   $('divNoLongerWantItem').show();
		   $('divSendItemWorthMore').hide();
		   break;
		default:  $('divMainText').hide();
	}
}

function LaunchTour() {	
	if (document.URL.indexOf("/home")==-1) { 
		// always start the tour on the home page	
		window.location.href = "http://" + ((location.host.indexOf("secure") >= 0) ? "www.swaptree.com/" : location.host + baseUrl) + "home/?tour=0"; }
	else { 
		fn_tour(0);
	}
}

//Import items into Trade List//
function AjaxImportItems(ISBN_UPC, Action) {
    current_ISBN_UPC = ISBN_UPC;
    current_Action = Action;
    var objItemCondDescription = $('taCondDesc_' + ISBN_UPC);
    var objItemCondition = $('pdCond_' + ISBN_UPC);
    objspanMessage = $('span_' + ISBN_UPC);
    objItemCondDescription.value = objItemCondDescription.value.replace(/type optional item description here/,"")
               
    if ((objItemCondition) && (objItemCondDescription)){
         if ((Action == 1) && ((objItemCondition.value == 5) || ((objItemCondition.value == 0) && (objItemCondDescription.value == '')))) {
            if (objItemCondition.value == 5) {
				objspanMessage.innerHTML = "<font color='red'>you must select a condition for the item </font>";
            } else {
				objspanMessage.innerHTML = "<font color='red'>you must provide an item description if condition is 'acceptable'</font>";
				objItemCondDescription.value = "type optional item description here"
            }
         } else {
		   objspanMessage.innerHTML = "";
           var pars = 'ISBN_UPC=' + ISBN_UPC + '&Action=' + Action + '&ItemCondition=' + objItemCondition.value + '&ItemCondDecscription=' + objItemCondDescription.value;
	       var myAjax = new Ajax.Request(baseUrl + 'AjaxImportItems.aspx', { method: 'get', parameters: pars, onSuccess: showImportResponse });
	     }
    }
 }
    
function showImportResponse(resp) {
    
	if (resp.responseText == "1") {
	     if (current_Action == 1) { //successfully inserted into TradeList
			$('pdCond_' + current_ISBN_UPC).hide();
			$('tdCondDescription_' + current_ISBN_UPC).hide();
			$('tdActionButtons_' + current_ISBN_UPC).innerHTML = "this item was successfully added to your have list";
		 } else  { //successfully removed from list of imported items
			  $('tblItem_'+ current_ISBN_UPC).hide();
		 }
	}
	else if(resp.responseText=="-1")//to do: failure reported by AjaxImportItems
	   {
	    
	   }	
	else //to do: potentially handle other 'responseText statuses' returned by AjaxImportItems
	  {
	   
	  }
}
//check status of shipping label(if it is generated successfully or not
var m_iMessageID=0;
var m_iTradeID=0;
function AjaxCheckSuccessOfLabel(iMessageID,iTradeID)
{
	$('UctrlSubMenu_divPageAlert').hide();
	m_iMessageID=iMessageID;
	m_iTradeID=iTradeID;
	window.setTimeout(function(){makeAjaxRequestForCheckSuccess();}, 1000);
}

function makeAjaxRequestForCheckSuccess()
{
	var pars = 'MessageID=' + m_iMessageID + '&TradeId=' + m_iTradeID;
	var myAjax = new Ajax.Request(baseUrl + 'AjaxCheckSuccessOfLabel.aspx', { method: 'get', parameters: pars, onSuccess: showMessageForLabel });
}

function showMessageForLabel(resp)
{	
	var labelStatus = deserializeJSON(resp.responseText);
	
	if (labelStatus == "" || !labelStatus.Transaction.IsProcessed)
	{			
		//if the first AJAX call was unable to find out whether transaction was successful or not, try another one
		//need to watch this to make sure it doesn't go into an infinite loop
		window.setTimeout(function(){makeAjaxRequestForCheckSuccess();}, 2000);
		return;
	}

	if(m_iMessageID >= 0) 
	{				
		if (((m_iMessageID!=0)&&(m_iMessageID!=1)&&(m_iMessageID!=2)&&(m_iMessageID!=6)&&(m_iMessageID!=7)) || (!labelStatus.Transaction.Details.IsSuccess))
		{
			//show error messages or user problems
			$("imgPageAlertImage").src='/images/alert_exlamation.jpg';
			$("UctrlSubMenu_spanPageAlert").className='pageAlertTextColorRed';
			$("UctrlSubMenu_divPageAlertTop").className='pageAlertTopCurvesRed';
			$("UctrlSubMenu_divPageAlertBottom").className='pageAlertBottomCurvesRed';
			$("UctrlSubMenu_divPageAlertInsideBox").className='pageAlertInsideBoxRed';												
		}
		
		if(!labelStatus.Transaction.Details.IsSuccess){
			$("divGeneratingLabel").hide(); //hide generating label message    
			$("UctrlSubMenu_divPageAlert").show(); //show page alert
			$("UctrlSubMenu_spanPageAlert").innerHTML = labelStatus.Transaction.Details.Message;
		} else {
			//set print links href to use tracking number. BE SURE TO SET HREF BEFORE SHOWING PRINT BUTTONS
			$("ucPrintLabel1_hypButtonLink").href = $("ucPrintLabel1_hypButtonLink").href + labelStatus.Transaction.Details.TrackingNumber;
			$("ucPrintLabel2_hypButtonLink").href = $("ucPrintLabel2_hypButtonLink").href + labelStatus.Transaction.Details.TrackingNumber;
			
			$("divGeneratingLabel").hide(); //hide generating label message    
			$("UctrlSubMenu_divPageAlert").show(); //show page alert
			$('divLabel').show(); //show label and print buttons
			$("UctrlSubMenu_spanPageAlert").innerHTML = labelStatus.Transaction.Details.Message;
		}
	}	
}

function deserializeJSON(responseText){
	if(responseText == ""){
		return "";
	}
	return eval('(' + responseText + ')');
}

	function AJAXgetAnswersFromFAQ() 
	{ 			   
		var tradeList = $('divTrades');
		var obj = $('ddlSubject');
		var spanMessage = $('spanMessage');
		
		switch(obj.value){
			case "1":
			case "2":
			case "7":						
				if(tradeList) {
					spanMessage.innerHTML = "";	
					tradeList.show();
				} else if(document.Form1.action.indexOf("showtrades=1") >= 0) {
					spanMessage.innerHTML = "<font color=\"red\">please enter the related trade number in your comments</font><br />";					
				} else {							
					document.Form1.action = document.Form1.action + ((document.Form1.action.indexOf("?") >= 0) ? "&" : "?") + "showtrades=1";
					document.Form1.submit();
				}						
				break;
			
			case "6":
				if(tradeList) {
					tradeList.hide();
				}
				spanMessage.innerHTML = "<font color=\"red\">please include item name and UPC/ISBN in your comments</font><br>";
				break;
			
			default:						
				if(tradeList) {
					tradeList.hide();
				}
				spanMessage.innerHTML = "";	
				break;
		}
		
		//Getting FAQ Answers on Contactus page. Put below message so if form posts we don't make an unnecessary ajax call		
		var answersFromFAQ = $('divSubjectFromFAQ');
		answersFromFAQ.hide();	   
	   
		new Ajax.Request(baseUrl + "WebFrmFAQ.aspx?topic="+obj.value, 
		{
			onSuccess : function(resp) {DisplayResultsFromFAQ(resp);}
			
		});
	}	
	
	function HideVAMMessage()
	{
	if($('valTrades'))
		{
		if($('valTrades').value != "")
			{
				$('valTrades').hide();
			}
		}
	}
		
	function DisplayResultsFromFAQ(resp) {
		if (resp.responseText.length > 0) 
		{	
			var spanSubjectFromFAQ = $('spanSubjectFromFAQ');
			var answersFromFAQ = $('divSubjectFromFAQ');
			answersFromFAQ.show();
			spanSubjectFromFAQ.innerHTML = resp.responseText;
		}
		else
		{
			answersFromFAQ.hide();
		}	 
	}