//advertise with us form validation
function advertForm(){
	if(document.getElementById('bname').value == ''){
		alert('Please Enter a Business Name');
		return;
	}
	if(document.getElementById('email').value == ''){
		alert('Please Enter an Email Address');
		return;
	}
	if(document.getElementById('fname').value == ''){
		alert('Please Enter a First Name');
		return;
	}
	if(document.getElementById('lname').value == ''){
		alert('Please Enter a Last Name');
		return;
	}
	if(document.getElementById('phone').value == ''){
		alert('Please Enter a Phone #');
		return;
	}
	if(document.getElementById('address').value == ''){
		alert('Please Enter a Address');
		return;
	}
	if(document.getElementById('city').value == ''){
		alert('Please Enter a City');
		return;
	}
	if(document.getElementById('zip').value == ''){
		alert('Please Enter a Zip Code');
		return;
	}

	
	
	
	var bname = document.getElementById('bname').value;
	var email = document.getElementById('email').value;
	var fname = document.getElementById('fname').value;
	var lname = document.getElementById('lname').value;
	var phone = document.getElementById('phone').value;
	var address = document.getElementById('address').value;
	var city = document.getElementById('city').value;
	var state = document.getElementById('state').value;
	var zip = document.getElementById('zip').value;
	var type = document.getElementById('type').value;
	var website = document.getElementById('website').value;
	var contact = document.getElementById('contact').value;
	
	var  res = document.getElementById('response');
	res.style.display = 'block';
	res.innerHTML = "<img src='lightbox/Assets/fbloader.gif'/>";	
	var req = new XMLHttpRequest();
	req.open("GET", 'advertForm.php?bname='+bname+'&email='+email+'&fname='+fname+'&lname='+lname+'&phone='+phone+'&address='+address+'&city='+city+'&state='+state+'&zip='+zip+'&type='+type+'&website='+website+'&contact='+contact);

    req.onreadystatechange = function()
    {
        if (req.readyState == 4 || req.readyState == 200)
        {
			if(req.responseText == 1){
				res.style.display = 'block';
				res.innerHTML = 'Your Message has been sent successfully. A representative will contact you shortly. Thank You.';
			}
			else{
				res.style.display = 'block';
				res.innerHTML = 'Your message could not be sent at this time.Please try again later. Thank You.';
			}
		}
    };
    req.send();
}

//voting functions
    function submitVote()
    {
        document.getElementById("votePageWrapper").style.display = "none"; // hide voting form
        var req = new XMLHttpRequest();
        var electionId = document.getElementById('election_id').value;
        var pageString = "vote_submit.php?election_id=" + document.getElementById('election_id').value + "&contestant_id="
             + getCheckedValue(document.election_form.contestant_id) + "&email=" + document.election_form.email.value + "&city=" + document.election_form.city.value + "&state=" + document.election_form.state.value;
        if (document.election_form.opt_in_everything_new_in_city.checked)
            pageString += "&opt_in_everything_new_in_city=true";
        if (document.election_form.newsletter.checked)
            pageString += "&newsletter=true";
        document.getElementById("voteResponseWrapper").innerHTML = "Submitting vote...";
        req.open("GET", pageString);
        req.onreadystatechange = function ()
            {
                if (req.readyState == 4 && req.status == 200)
                    voteSuccess(req.responseText, electionId);
                else
                    document.getElementById("voteResponseWrapper").innerHTML = "";
            }
        req.send();
    }
    
    function voteSuccess(responseText, electionId)
    {        
        document.getElementById("voteResponseWrapper").innerHTML = responseText;
        document.getElementById("generatedElectionImageContainer").innerHTML = "<img width='230' height='120' src='generated_election_images/" + electionId + ".png?date=" + ((new Date).getTime()) + "' alt='Contest results' />";
    
    }
    
    function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}
//time functions
var secondsRemaining = 0;
function initCountdown(startingSecondsRemaining)
{
	secondsRemaining = startingSecondsRemaining;
	setTimeout("updateCountdown();", 1000);
}
function secondsToTimeFormat(totalSeconds)
{
	var seconds = totalSeconds;
	var minutes = 0;
	var hours = 0;
	var days = 0;
	
	if (seconds > 59)
	{
		minutes = Math.floor(seconds/60);
		seconds = seconds % 60;
	}
	
	if (minutes > 59)
	{
		hours = Math.floor(minutes/60);
		minutes = minutes % 60;
	}
	
	if (hours > 23)
	{
		days = Math.floor(hours/24);
		hours = hours % 24;
	}
	
	var timeString = "";
	
	if (days > 0)
		timeString += days + " days, ";
		
	if (hours < 10)
		timeString += "0";
	timeString += hours;
	timeString += ":";
	
	if (minutes < 10)
		timeString += "0";
	timeString += minutes;
	timeString += ":";
	
	if (seconds < 10)
		timeString += "0";
	timeString += seconds;
	
	return timeString;
}
/*
	updateCountdown()
	to be called once per second to decrement the countdown's remaining seconds and to update the time displayed
*/
function updateCountdown()
{
	secondsRemaining--;
	if (secondsRemaining < 0)
		secondsRemaining = 0;
	if (secondsRemaining != 0 && secondsRemaining < 1800 && secondsRemaining % 2 == 1)
		document.getElementById("countdownTimer").innerHTML = "<strong>Offer Expires In</strong><br /><span style='color:#FB8501;'>" + secondsToTimeFormat(secondsRemaining) + "</span>";
	else
		document.getElementById("countdownTimer").innerHTML = '<strong>Offer Expires In</strong><br />'+secondsToTimeFormat(secondsRemaining);
	if (secondsRemaining > 0)
		setTimeout("updateCountdown();", 1000);
}
// city search functions
function filterCouponsAndDeals()
{
 document.getElementById('back2city').style.display = 'block';
    var radius = document.searchForm.radius.value;
    var city = document.searchForm.city.value;
    var state = document.searchForm.state.value;
    var keywords = document.searchForm.keywords.value;
    var category = document.searchForm.category.value;
    var zip = document.searchForm.zip.value;
    var req = new XMLHttpRequest();
    req.open("GET", "search_coupons_and_deals.php?zip=" + zip + "&city=" + city + "&state=" + state + "&radius=" + radius + "&keywords=" + keywords + "&category=" + category);
	document.getElementById("couponAndDealListingWrapper").innerHTML = '<br /><br /><br /><center><img src="images/loading.gif" alt="loading" /><br /><span class="citycontentBoxbottom" style="background:none">Searching...</span></center><br /><br />';
    req.onreadystatechange = function()
    {
        if (req.readyState == 4 || req.readyState == 200)
        {
            document.getElementById("couponAndDealListingWrapper").innerHTML = req.responseText;
        }
    };
    req.send();
	
document.searchForm.category.value = '';
}
function filterFeaturedOffers()
{
    var radius = document.searchForm.radius.value;
    var city = document.searchForm.city.value;
    var state = document.searchForm.state.value;
    var keywords = document.searchForm.keywords.value;
    var category = document.searchForm.category.value;
    var zip = document.searchForm.zip.value;
    var req = new XMLHttpRequest();
    req.open("GET", "search_featured_offers.php?zip=" + zip + "&city=" + city + "&state=" + state + "&radius=" + radius + "&keywords=" + keywords + "&category=" + category);
    req.onreadystatechange = function()
    {
        if (req.readyState == 4 || req.readyState == 200)
        {
			document.getElementById("featuredListingWrapper").style.overflowY = "scroll";
			document.getElementById("featuredListingWrapper").style.height = "375px";
            document.getElementById("featuredListingWrapper").innerHTML = req.responseText;
        }
    };
    req.send();
}
function filterByCategory(category)
{
    document.searchForm.category.value = category;
    filterCouponsAndDeals();
}
//shopping cart functions
function fadeInContinue(amount)
{
    var shoppingCartDiv = document.getElementById("sidebarShoppingCartContainer");
    shoppingCartDiv.style.opacity = amount;
    if (amount < 1)
    {
        var newAmount = amount + 0.01;
        setTimeout("fadeInContinue(" + newAmount + ");", 1);
    }
}
function fadeInSideShoppingCart()
{
    var shoppingCartDiv = document.getElementById("sidebarShoppingCartContainer");
    if (document.getElementById('sidebarShoppingCartContainer').style.display != 'block')
    {
        shoppingCartDiv.style.opacity = 0.0;
        document.getElementById('sidebarShoppingCartContainer').style.display = 'block';
        setTimeout("fadeInContinue(0.01);", 1);
    }
}
function addToCart(id, itemType)
{
    if (itemType == 'coupon')
    {
 		var couponQty = document.getElementById('couponQty').value;
		
		if(couponQty < 1){
			couponQty = 1;
		}
        var req = new XMLHttpRequest();
		
        req.open("GET", "addtocart.php?coupon_id=" + id + "&qty="+couponQty, true)
        req.onreadystatechange = function()
        {
            if (req.readyState == 4 && req.status == 200)
			{
                //refreshShoppingCart();
//				alert('Coupon Added to Cart Successfully');
				window.top.location = 'checkout.php';
			}
        }
        req.send();
    }
    else if (itemType == 'deal')
    {
		var dealQty = document.getElementById('dealQty').value;
		if(dealQty < 1){
			dealQty = 1;
		}
        var req = new XMLHttpRequest();
        req.open("GET", "addtocart.php?deal_id=" + id+ "&qty="+dealQty, true)
        req.onreadystatechange = function()
        {
            if (req.readyState == 4 && req.status == 200)
			{
                //refreshShoppingCart();
//				alert('Deal Added to Cart Successfully');
				window.top.location = 'checkout.php';
			}
        }
        req.send();
    }
    else if (itemType == 'featured')
    {
		var featuredQty = document.getElementById('featuredQty').value;
		if(featuredQty < 1){
			featuredQty = 1;
		}
        var req = new XMLHttpRequest();
        req.open("GET", "addtocart.php?featured_id=" + id + "&qty="+featuredQty, true)
        req.onreadystatechange = function()
        {
            if (req.readyState == 4 && req.status == 200)
			{
                //refreshShoppingCart();
//				alert('Featured Offer Added to Cart Successfully');
				window.top.location = 'checkout.php';
			}
        }
        req.send();
    }
    else
        alert('Invalid item type in addToCart()');
}
function removeFromCart(id, itemType)
{
    if (itemType == 'coupon')
    {
        var req = new XMLHttpRequest();
        req.open("GET", "removefromcart.php?coupon_id=" + id, true)
        req.onreadystatechange = function()
        {
            if (req.readyState == 4 && req.status == 200)
			{
                refreshShoppingCart();
				thisNode = document.getElementById('couponRow'+id);
  				thisNode.parentNode.removeChild(thisNode);
			}
        }
        req.send();
    }
    else if (itemType == 'deal')
    {
        var req = new XMLHttpRequest();
        req.open("GET", "removefromcart.php?deal_id=" + id, true)
        req.onreadystatechange = function()
        {
            if (req.readyState == 4 && req.status == 200)
			{
                refreshShoppingCart();
				thisNode = document.getElementById('dealRow'+id);
  				thisNode.parentNode.removeChild(thisNode);
				updateTotalPrice();
			}
        }
        req.send();
    }
    else if (itemType == 'featured')
    {
        var req = new XMLHttpRequest();
        req.open("GET", "removefromcart.php?featured_id=" + id, true)
        req.onreadystatechange = function()
        {
            if (req.readyState == 4 && req.status == 200)
			{
                refreshShoppingCart();
				thisNode = document.getElementById('featuredRow'+id);
  				thisNode.parentNode.removeChild(thisNode);
				updateTotalPrice();
			}
        }
        req.send();
    }
    else
        alert('Invalid item type in removeFromCart()');
}
function couponQtyUpdate(id, fieldNum){
	var req = new XMLHttpRequest();
	var field = document.getElementById('cartCouponQty'+fieldNum);
	var qty = field.value;
        req.open("GET", "updateCart.php?coupon_id=" + id + "&qty=" + qty, true)
        req.onreadystatechange = function()
        {
            if (req.readyState == 4 && req.status == 200)
                refreshShoppingCart();
				field.value = req.responseText;
				
        }
        req.send();
		
}
function dealQtyUpdate(id, fieldNum){
	var req = new XMLHttpRequest();
	var field = document.getElementById('cartDealQty'+fieldNum);
	var qty = field.value;
        req.open("GET", "updateCart.php?deal_id=" + id + "&qty=" + qty, true)
        req.onreadystatechange = function()
        {
            if (req.readyState == 4 && req.status == 200)
			{
                refreshShoppingCart();
				var deal = req.responseXML.getElementsByTagName('deal');
				field.value = deal[0].getElementsByTagName('quantity')[0].firstChild.nodeValue;
				document.getElementById('dealSubTotal'+fieldNum).innerHTML = deal[0].getElementsByTagName('subtotal')[0].firstChild.nodeValue;
				updateTotalPrice();
			}
        }
        req.send();
		
}
function featuredQtyUpdate(id, fieldNum){
	var req = new XMLHttpRequest();
	var field = document.getElementById('cartFeaturedQty'+fieldNum);
	var qty = field.value;
        req.open("GET", "updateCart.php?featured_id=" + id + "&qty=" + qty, true)
        req.onreadystatechange = function()
        {
            if (req.readyState == 4 && req.status == 200)
			{
                refreshShoppingCart();
				var featured = req.responseXML.getElementsByTagName('featured');
				field.value = featured[0].getElementsByTagName('quantity')[0].firstChild.nodeValue;
				document.getElementById('featuredSubTotal'+fieldNum).innerHTML = featured[0].getElementsByTagName('subtotal')[0].firstChild.nodeValue;
				updateTotalPrice();
			}
        }
        req.send();		
}
//update total price does not have anything to do with the total that is passed to paypal. it is strictly for displaying the total price on the checkout page
function updateTotalPrice(){
var total = 0;	
//deal prices
var dealDivs = [];
//finds and indexs all the subtotal divs
for(j=0;j<100;j++){
	if(document.getElementById('dealSubTotal'+j) != null){
		dealDivs.push(j);		
	}
}
//goes through existing subtotal divs and adds subtotal to total
for(i=0;i<dealDivs.length; i++){
	if(document.getElementById('dealSubTotal'+dealDivs[i]) != null)
	{				
		var value = document.getElementById('dealSubTotal'+dealDivs[i]).innerHTML;
		value = value.replace('$', '');		
		total += parseFloat(value);	
		
	}
}
//featured prices
var featuredDivs = [];
//finds and indexs all the subtotal divs
for(j=0;j<100;j++){
	if(document.getElementById('featuredSubTotal'+j) != null){
		featuredDivs.push(j);
	}
}
//goes through existing subtotal divs and adds subtotal to total
for(i=0;i<featuredDivs.length; i++){
	if(document.getElementById('featuredSubTotal'+featuredDivs[i]) != null)
	{
		var value = document.getElementById('featuredSubTotal'+featuredDivs[i]).innerHTML;
		value = value.replace('$', '');
		total += parseFloat(value);	
		
	}
}
document.getElementById('totalPrice').innerHTML = '$'+total.toFixed(2);
	
}

function ajaxDivSwitch(oldDivId, newDivId, processingText, newPageURL, refreshCart)
{
    if (oldDivId != '')
        document.getElementById(oldDivId).style.display = 'none';
    
	document.getElementById(newDivId).innerHTML = processingText;
    var req = new XMLHttpRequest();
    req.open("GET", newPageURL, true)
    req.onreadystatechange = function()
    {
        if (req.readyState == 4 && req.status == 200)
        {
            document.getElementById(newDivId).innerHTML = req.responseText;
            if (refreshCart)
                refreshShoppingCart();
        }
    }
    req.send();
}
function refreshShoppingCart()
{
    // todo: this function should update the contents of the shopping cart div
    ajaxDivSwitch('', 'sidebarShoppingCartContainer', 'Updating shopping cart...', 'get_shopping_cart.php', false);
    fadeInSideShoppingCart();
}
