/*
 * Author Jonathan Samples
 * Created April 17, 2008
 * 
 * This file will be used to keep all ajax related functionality
 */
 
 function getXMLHttpObject()
{
	var xmlHttp;
	try
	{
	  // Firefox, Opera 8.0+, Safari
	  xmlHttp=new XMLHttpRequest();
	}
	catch (e)
	{
	  // Internet Explorer
	  try
	  {
		  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	  }
	  catch (e)
	  {
	  	try
	    {
	      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
	    }
	    catch (e)
	    {
	      alert("Your browser does not support AJAX!");
	      return false;
	    }
	  }
	}
	return xmlHttp;
 }
 
 
 
 function postRating(userId, offerId, rating){
 	var req = getXMLHttpObject();
 	var openString = "/includes/form_handlers/ratings.php?cid="+offerId+"&rating="+rating;
 	req.open("GET",openString,true);
 	req.send(null);
 	
 	var ele = document.getElementById('rating_title_'+offerId);
 	ele.innerHTML = "My Rating";
 }
 
 function postClip(offerId, couponId){
 	var req = getXMLHttpObject();
 	req.onreadystatechange = function(){
 		if(req.readyState == 4){
 			if(currentView)
 				refreshClipList(currentView);
 			var regxp = new RegExp("2");
			if(regxp.test(req.responseText)){
				window.location.reload(true);
			}
 		}
 	}
 	var openString = "/includes/form_handlers/clipping.php?clip="+couponId;
 	req.open("GET",openString,true);
 	req.send(null);
 	
 	initLoadingClipList();
 	
 	coupons[couponId] = true;
 	 	
 	toggleSavedUnsaved(couponId, true);
 }
 
 function toggleSavedUnsaved(couponId, is_saved){

 	var saved = document.getElementById('saved_'+couponId);
 	var unsaved = document.getElementById('unsaved_'+couponId);
 	var pop_save_button = document.getElementById('pop_clip_button'+couponId);
 	var pop_unsave_button = document.getElementById('pop_unclip_button'+couponId);
 	
	if(is_saved){ // currently saved
	 	//alert("is_saved is true");
	
		if(saved){
			saved.style.height = "";
			saved.style.overflow = "";
		}
		if(unsaved){
			unsaved.style.height = "0px";
			unsaved.style.overflow = "hidden";
		}
		if(pop_save_button){
			pop_save_button.style.height = "0px";
			pop_save_button.style.overflow = "hidden";
		}
		if(pop_unsave_button){
			pop_unsave_button.style.height = "";
			pop_unsave_button.style.overflow = "";
		}
		
	}
	else{
		//alert("is_saved is false");
		if(unsaved){
			unsaved.style.height = "";
			unsaved.style.overflow = "";
		}
		if(saved){
			saved.style.height = "0px";
			saved.style.overflow = "hidden";
		}
		if(pop_save_button){
			pop_save_button.style.height = "";
			pop_save_button.style.overflow = "";
		}
		if(pop_unsave_button){
			pop_unsave_button.style.height = "0px";
			pop_unsave_button.style.overflow = "hidden";
		}
	}
 }
 
 function postUnclip(couponId, id){
 	var req = getXMLHttpObject();
 	req.onreadystatechange = function(){
 		if(req.readyState == 4){
 			refreshClipList(currentView);
 		}
 	}
 	var openString = "/includes/form_handlers/clipping.php?unclip="+couponId;
 	req.open("GET",openString,true);
 	req.send(null);
 	
 	initLoadingClipList();
 	
 	coupons[couponId] = false;
 	
 	toggleSavedUnsaved(couponId, false);
 }
 
 function postSendSMS(){
 	var req = getXMLHttpObject();
 	var openString = "/includes/form_handlers/sendSMS.php";
 	req.open("GET",openString,true);
 	req.send(null);
 }
 
  function postSendVefifySMS(){
 	var req = getXMLHttpObject();
 	var openString = "/includes/form_handlers/reg_full.php?vsms=1";
 	req.open("GET",openString,true);
 	req.send(null);
 }
 
 
 function initLoadingClipList(){
 	var ele = document.getElementById('clip_list');
 	if(!ele) return;
 	var loadImg = document.createElement('img');
 	loadImg.src="/includes/templates/master/images/loader.gif";
 	loadText = document.createElement('h2');
 	loadText.className="title3";
 	loadText.appendChild(document.createTextNode("Checking for Updates"));
 	ele.innerHTML = "";
 	ele.appendChild(loadImg);
 	ele.appendChild(loadText);
 }
 
 var inProcess = false;
 var currentView = 5;
 function refreshClipList(lm){
 	var ele = document.getElementById('clip_list');
 	if(!ele) return;
 	if(inProcess) return;
 	inProcess = true;
 	currentView = lm;
 	var req = getXMLHttpObject();
 	req.onreadystatechange = function(){
 		if(req.readyState == 4){
 			var ele = document.getElementById('clip_list');
 			if(!ele) return;
 			ele.innerHTML = req.responseText;
 			inProcess = false;
 		}
 	}
 	var openString = "/includes/tiles/saved_offers.php?lm="+lm;
 	//alert(openString);
 	req.open("GET",openString,true);
 	req.send(null);
 	
 	initLoadingClipList();
 	
 	
 }
 
 function checkAvailability(mercId){
 	var req = getXMLHttpObject();
 	req.onreadystatechange = function(){
 		if(req.readyState == 4){
 			var ele = document.getElementById('avail_box');
 			ele.innerHTML = req.responseText+"<br/>";
 			inProcess = false;
 		}
 	}
 	var ca_city = document.getElementById("ca_city");
 	var ca_state = document.getElementById("ca_state");
 	var ca_zip = document.getElementById("ca_zip");
 	var openString = "/includes/form_handlers/check_avail.php?merchantId="+mercId+"&ca_zip="+ca_zip.value+"&ca_city="+ca_city.value+"&ca_state="+ca_state.options[ca_state.selectedIndex].value;
 	//alert(openString);
 	req.open("GET",openString,true);
 	req.send(null);
 	
 	var avail_box = document.getElementById("avail_box");
 	avail_box.innerHTML = "<img src=\"/includes/templates/master/images/loader.gif\" /><br/><span class=\"title2\">Checking Availability</span>";
 	
 	toggleAvailForm();
 	return false;
 }
 
 function toggleAvailForm(){
 	var avail_form = document.getElementById("avail_form");
 	
 	// The availability form is hidden
 	if(avail_form.style.height == "0px"){
 		avail_form.style.overflow = "";
	 	avail_form.style.height = "";
	 	avail_form.style.visibility = "visible";
 	
 	}
 	else{
 		avail_form.style.overflow = "hidden";
	 	avail_form.style.height = "0px";
	 	avail_form.style.visibility = "hidden";
 	}

 
 }
 
 function removeCard(mid){
 	var req = getXMLHttpObject();
 	req.onreadystatechange = function(){
 		if(req.readyState == 4){
 			var pop_div = document.getElementById("confirm_card_body_"+mid);
 			if(req.responseText == 0){ // Succesfully removed card
 				closeDiv(10,"lc_"+mid);
 				wm.closeOpenWindow();
 				
 				NUM_CARDS--;
 				if(NUM_CARDS == 0)
 					openDiv(20,"no_cards_message",40);
 			}
 			else if(req.responseText == -1){
 				pop_div.innerHTML = "<strong>Cannot Remove Card</strong><br/>This card is currently pending approval, please wait until the card has been approved before removing.";
 			}
 			else if(req.responseText == -2){
 				pop_div.innerHTML = "<strong>Cannot Remove Card</strong><br/>You currently have offers pending approval to be added to your card. Please try removing again after the offers have been added.";
 			}
 			else{
 				pop_div.innerHTML = "<strong>Cannot Remove Card</strong><br/>We are currently experiencing technical difficulties ("+req.responseText+").  Please try again soon.";
 			}
 		}
 	}
 	var openString = "/includes/form_handlers/loyalty.php?remove="+mid;
 
 	req.open("GET",openString,true);
 	req.send(null);
 	var pop_div = document.getElementById("confirm_card_body_"+mid);
 }
 
 
 
 function postAddCard(mid, offerId, doingAssoc){
 	var req = getXMLHttpObject();
 	req.onreadystatechange = function(){
 		if(req.readyState == 4){
 			var error = document.getElementById("add_card_error_"+mid+"_"+offerId);
 			error.className = "error";
 			var body = document.getElementById("add_card_cont_"+mid+"_"+offerId);
 			var main_body = document.getElementById("add_card_elements_"+mid+"_"+offerId);
 			var top = document.getElementById("add_card_top_"+mid+"_"+offerId);
 			var form_id = "add_card_form_"+mid+"_"+offerId;
 			var form = document.getElementById(form_id);
 			var status = document.getElementById("card_status_"+mid+"_"+offerId);
 			var success = document.getElementById("add_card_success_"+mid+"_"+offerId);
 			var cardnum_holder = document.getElementById("cardnum_holder_"+mid+"_"+offerId);
 			var cardalt_holder = document.getElementById("cardalt_holder_"+mid+"_"+offerId);
 			
 			if(req.responseText == 1){ // Success
 				if(success){
 					if (main_body)
 					{
 						main_body.innerHTML = "";	
 					}	
 					if (top)
 					{
 						top.innerHTML = "";
 					}	
 					if(cardnum_holder){ cardnum_holder.style.height="0px"; cardnum_holder.style.visibility = "hidden";}
 					if(cardalt_holder){ cardalt_holder.style.height="0px"; cardalt_holder.style.visibility = "hidden";}

 					success.style.display = "block";
 					error.style.visibility="hidden";
	 			}
	 			else if(form && status){
	 				form.innerHTML = "";
	 				status.innerHTML = "Pending";
	 				if(cardnum_holder){ cardnum_holder.style.height="0px"; cardnum_holder.style.visibility = "hidden";}
	 				if(cardalt_holder){ cardalt_holder.style.height="0px"; cardalt_holder.style.visibility = "hidden";}

	 			}
	 			else{
	 				if(!form)
	 					alert("form not legit:"+form_id);
	 				else
	 					alert("status not legit");
	 			}
 			}
 			else if(req.responseText == 2){ // already in use
 				error.innerHTML = "We're sorry, but that card is already assigned to another Cellfire account. Please check the number and try again or click <a href=\"javascript: window.location = document.location.pathname + '?faq=1&faq_q=qCardInUse#qCardInUse'\">here</a> to learn why you might be getting this message.";
 				error.style.visibility = "visible";
 			}
 			else if(req.responseText == 3){ // Checksum failed
 				error.innerHTML = "Sorry, that is not a valid number, please enter the card number or the phone number that is associated with your card.";
 				error.style.visibility = "visible";
 			}
 			else if(req.responseText == 4){ // Empty fields
 				error.innerHTML = "Please enter your card number or the phone number that is associated with your card.";
 				error.style.visibility = "visible";
 			}
			/*  uncomment when ready from coupon server
			else if(req.responseText == 30)
			{
				error.innerHTML = "Sorry, that is not a valid number, please enter the card number that is associated with your card.";
				error.style.visibility = "visible";
			}
			else if(req.responseText == 31)
			{
				error.innerHTML = "We are unable to find your card account. Check the number and try again. New card holders: it can take up to 5 business days before your card account can be accessed. Need Help? Contact support. ";
				error.style.visibility = "visible";
			}
			else if(req.responseText == 32)
			{
				error.innerHTML = "We're unable find a card account matching that {ALTID}. Please check the number and try again. Be sure to use the {ALTID} you give at checkout or enter your card number instead. Need Help? Contact support.";
				error.style.visibility = "visible";
			}
			*/ 			
			else{
 				if(body){
					body.innerHTML = "";
	 				body.appendChild(document.createTextNode("Sorry the system is currently unavailable."));
	 				body.appendChild(document.createElement("br"));
	 				var button = document.createElement("input");
	 				button.type = "image";
	 				button.src = "/includes/templates/master/images/button_ok.jpg";
	 				button.onclick = function(){
	 					closePopUp("add_card_"+mid+"_"+offerId);
	 					window.location.reload(true);
	 				}
	 				body.appendChild(button); 		
	 			}
	 			else if(form){
	 				error.innerHTML = "Sorry, the system is unavailable. Please try again later.";
	 			}	
 			}
 		}
 	}
 	var cardNum = document.getElementById("lc_number_"+mid+"_"+offerId).value;
 	var altNum = document.getElementById("lc_alt_"+mid+"_"+offerId).value;
 	altNum = trim_phone_number(altNum);
 	var openString = "/includes/form_handlers/loyalty.php?mid="+mid+"&offer="+offerId+"&cnum="+cardNum+"&altnum="+altNum + "&doingAssoc=" + doingAssoc;
 
 	req.open("GET",openString,true);
 	req.send(null);
 }
 function trim_phone_number(phone_num){
 	var phone=phone_num.replace('(','');
 	phone=phone_num.replace(')','');
 	phone=phone_num.replace('-','');
 	phone=phone_num.replace(' ','');
 	phone=phone_num.replace('.','');
 	return phone;
 }
 function postView(cid){
  	var req = getXMLHttpObject();
  	var openString = "/includes/form_handlers/log_view.php?cid="+cid;
  	//alert(openString);
  	req.open("GET",openString,true);
  	req.send(null);
 }
 
 function postUnassocOffer(offerId)
 {
   	var req = getXMLHttpObject();
   	var openString = "/includes/form_handlers/clipping.php?unassoc=" + offerId;
   	//alert(openString);
   	req.onreadystatechange = function()
   		{
		 		if(req.readyState == 4)
		 		{
					var offerId = req.responseText;
					var ele = document.getElementById("assoc_coupon_" + offerId);
					if (ele)
					{
						closeDiv(10, "assoc_coupon_" + offerId);
					}	
				}	
   		}	
   	req.open("GET",openString,true);
   	req.send(null);

	 	initLoadingClipList();
 }
 
 function postAssocOffer(offerId, merchantId)
 {
		var req = getXMLHttpObject();
		var openString = "/includes/form_handlers/clipping.php?assoc=" + offerId + "&assoc_merch=" + merchantId;
		//alert(openString);
		req.onreadystatechange = function()
			{
				window.location='/account_overview.php?update=y';
			}	
		req.open("GET",openString,true);
		req.send(null);

	 	initLoadingClipList();

 }
 
  function getLocations(mid, zip){
 	var req = getXMLHttpObject();
 	req.onreadystatechange = new Function(
 		"if(req.readyState == 4){"+
 			"var ele = document.getElementById(\"merc_loc_pop_body_"+mid+"_"+zip+");"+
 			"ele.innerHTML = req.responseText+\"<br/>\";"+
 		"}"
 	);
 	
 	var openString = "/includes/tiles/merc_locations_by_zip.php?mid="+mid+"&zip="+zip;
 	//alert(openString);
 	req.open("GET",openString,true);
 	req.send(null);
 	
 	return false;
 }
 
 	function createAjaxPostParameters(parameters) {
		var postParameters = "";
		for (var i = 0; i < parameters.length; i++) {
			if (i == 0 ) {
				postParameters += parameters[i]['name'] + "=" +encodeURI( parameters[i]['value'] );
			} else {
				postParameters += "&" + parameters[i]['name'] + "=" +encodeURI( parameters[i]['value'] );
			}
		}
		return postParameters;
	}
 