function addTag(tagField, tagName){
    if (tagName.indexOf(" ") >= 0) {
        tagName = '"' + tagName + '"';
    }
    if (tagField.val()) {
        tagField.val(tagField.val() + " " + tagName);
        return;
    }
    tagField.val(tagName);
}

function popUpTags(data){
	var tags;
	if(data.responseObj) {
		tags = data.responseObj["tags"];
	} else {
		tags = data["tags"];
	}
    $('#allTags').find("option").remove();
    for (var i = 0; i < tags.length; i++) {
        $('#allTags').append(new Option(tags[i]));
    }
    $('#allTagsDiv').show();
}

function allTags(service){
    ajaxButtonRequest(service, {action: 'allTags'}, popUpTags, logit);
}

function loadTags(service, uid, target){
    ajaxButtonRequest(service, {'action': 'loadTags', 'uid': uid, 'target': target}, _loadTags, logit);
}

function _loadTags(data) {
	logit(data);
	$('#' + data['target']).val(data['tags']);
	return false;
}


function submitDonation(formId){
	var form = document.getElementById(formId);
	setAction($('#' + formId), "savePending");
    var donation_amount = $('#donation_amount').val();
    if (donation_amount.length < 1 || parseInt(donation_amount) <= 0) {
    	alertMessage("You must specify a donation amount.");
    return false;
    }
    ajaxButtonClick('donate.service', formId, _savePending, logit, true);
    return false;
}

function submitPass(formId){
	var form = document.getElementById(formId);
	setAction($('#' + formId), "savePending");
    
    var pass_name = $('#pass_name').val();
    if (pass_name.length < 1) {
    	alertMessage("You must specify a name for the pass.");
    	return false;
    }
    ajaxButtonClick('pass.service', formId, _savePending, logit, true);
    return false;
}

function submitFestival(formId){
    try {
        var form = document.getElementById(formId);
        var quantity = $(form).find("input[name='reserveonline_quantity']").val()
        
        if (quantity > 0) {
            setAction($('#' + formId), "savePending");
            ajaxButtonClick('reserve.service', formId, _savePending, logit, true);
        }
        else {
            alertMessage("You must specify the number of tickets to purchase.");
        }
        return false;
    } 
    catch (e) {
        alertMessage(e);
        return false;
    }
}

function submitReserveOnline(){
    try {
        if (!validate(document.getElementById('editreservation_form'))) {
            return false;
        }
        
        var showUid = $('#reserveonline_show_uid').val();
        if (showStatus[showUid]["is_soldout"] == 1 ||
        showStatus[showUid]["is_closed"] == 1) {
            _showPrice();
            return false;
        }
        
        var method = $("input[name='reserveonline_is_paid']:checked").val();
        if (method != "paypal") {
            $('#__reserve_only').val('True');
        }
        setAction($('#editreservation_form'), "savePending");
        ajaxButtonClick('reserve.service', 'editreservation_form', _savePending, logit, true);
        return false;
        
    } 
    catch (e) {
        alertMessage(e);
        return false;
    }
    
}

function submitReserveFree(){
    try {
        if (!validate(document.getElementById('editreservation_form'))) {
        	return false;
        }
        
         var showUid = $('#reserveonline_show_uid').val();
         if (showStatus[showUid]["is_soldout"] == 1 || showStatus[showUid]["is_closed"] == 1) {
        	 _showError();
        	 return false;
         }
        return true;
    } 
    catch (e) {
        logit(e);
        return false;
    }
    
}

function _showError(){
    var show = document.getElementById("reserveonline_show_uid");
    
    var option = show.options[show.selectedIndex];
    var uid = option.value;
    
    clearErrors('editreservation_form');
    
    var statuses = showStatus[uid];
    if (statuses["is_cart_pending"] == 1) {
	price.style.display = 'none';
	addError("reserveonline_quantity", messages["cart_pending_message"]);
    } else if (statuses["is_soldout"] == 1) {
    	price.style.display = 'none';
    	addError("reserveonline_quantity", messages["soldout_message"]);
    } else if (statuses["is_closed"] == 1) {
    	price.style.display = 'none';
    	addError("reserveonline_quantity", messages["closed_message"]);
    }
}

function _savePending(response){
    try {
        showForcefield();
        if (response["not_enough_tickets"] == "True") {
            alertError("There are not enough tickets left to fulfill your order.");
            clearForcefield();
            return false;
        }
        if (response["__error"]) {
            alertError(response["__error"]);
            clearForcefield();
            return false;
        }
        if (response["__shopping_cart"] == "True") {
            if (response["changed_quantity"] == "True") {
            	clearForcefield();
                alertMessage("You have added a duplicate item to your cart. Please verify the quantity is what you intended.", function() {
                	document.location = basepath + 'editcart.html?PHPSESSID=' + response["PHPSESSID"];
                });
                return false;
            }
            
            document.location = basepath + 'editcart.html?PHPSESSID=' + response["PHPSESSID"];
            return false;
        }
        if (response["__inline_shopping_cart"] == "True" && response["__inline_shopping_cart_callback"]) {
        	var callback = window[response["__inline_shopping_cart_callback"]];
        	callback(response);
        	return false;
        }
        if (response["__checkout_form"] == "True") {
            // should only get here if we use authorize and don't have a shopping cart
            top.location.href = basepath + 'checkout.html?PHPSESSID=' + response["PHPSESSID"];
            return false;
        }
        if (response["__reserve_only"] == "True") {
            document.location = response["return"];
            return false;
        }
            
        
        disableButtons(true);
        updatePaymentForm(response);
        
        var form = $('#payment_form');
        form.submit();
    } 
    catch (e) {
    	logit(e);
        alertMessage(e);
       
    }
}

function updatePaymentForm(post) {
    var form = $('#payment_form');
    form.html("");
    
    for (key in post) {
        var value = post[key];
        if (key.indexOf("~") >= 0) {
            key = key.substr(key.indexOf("~") + 1);
        }
        addInput(form, key, value);
    }
}

function addInput(form, name, value){
    var input = $(document.createElement("INPUT"));
    input.attr("type", "hidden");
    input.attr("name", name);
    input.val(value);
    form.append(input);
}

function _handleSubmit(data, status, transport){
    try {
        logit(data);
        alertMessage(data);
    } 
    catch (e) {
        alertError(e);
    }
}

function deleteItem(item){
    $('#delete').val(item);
    setAction($('#shopping_cart_form'), 'deleteItem');
    return true;
}

function deleteCode(item){
    $('#delete').val(item);
    setAction($('#shopping_cart_form'), 'deleteCode');
    return true;
}


function checkout(sessionid, canCheckout){
	if(canCheckout) {
		top.location.href = basepath + 'checkout.html?PHPSESSID=' + sessionid;
		return false;
	}
	if($('#total_amount').html() == '$ 0') {
		top.location.href = basepath + 'checkout.html?PHPSESSID=' + sessionid;
		return false;
	}
	// refresh shopping cart and populate form
	
	ajaxButtonRequest("editcart.service", {action: 'viewCart'}, function(data) {
		if(data.responseCode == 500) {
			clearForcefield(data);
			top.location.href = basepath + 'editcart.html?PHPSESSID=' + sessionid + "&msg=" + data.responseObj;
			return;
		}
        disableButtons(true);
        updatePaymentForm(data.responseObj.post);
        
        var form = $('#payment_form');
        form.submit();
	}, function(data) {
		clearForcefield(data);
		alertError("Error checkout out.");
	}, true);
    return false;
}

function showComment(el){
    	hideComment();
    
    	$(el.parentNode).append("<div class=\"comment\" id=\"__comment\"><div class=\"titlebar\"><a onclick=\"return hideComment();\" href=\"#\"><img alt=\"close window\" src=\""
    			+ imagepath
    			+ "close.gif\" /></a></div><div class=\"commentText\">"
    			+ el.getAttribute("title") + "</div></div>");
    	return false;
}

function hideComment(){
	var comment = $('#__comment');
	if(comment.length == 1) {
		comment.detach();
	}
	return false;
}

function previewProduction(){
    disableButtons(true);
    try {
        var form = $('#previewproduction_form');
        form.innerHTML = "";
        
        var data = $('#detailsTab_description').ckeditor().getData();
        logit(data);
        var response = $('editproduction_form').serialize(true);
        for (key in response) {
            var value = response[key];
            if (key == "action") {
                value = "preview";
            }
            else 
                if (key == "detailsTab_description") {
                    value = data;
                }
            addInput(form, key, value);
        }
        form.submit();
    } 
    catch (e) {
        alertMessage(e);
    }
    finally {
        disableButtons(false);
    }
}

function generateOneTimeCode(){
    document.location = "http://www.facebook.com/code_gen.php?api_key=0d38507daaacc36f9ccf3de5bdcdf1fb&v=1.0";
}


function facebookView(){

     if (!$('#memberPanel_facebook_id').val()) {
    	 alertError("You must specify a facebook id.");
    	 return false;
     }
     window.open("http://www.facebook.com/profile.php?id=" + $('#memberPanel_facebook_id').val());
}
function facebookLookup() {
	if(!FB) {
		alertError("You're not logged into Facebook.");
		return;
	}
	var name = $('#memberPanel_first_name').val() + ' ' + $('#memberPanel_last_name').val();
	FB.api('/search?type=user&q=' + name, function(response) {
		
		var users = [];
		for(var i = 0; i < response.data.length; i++) {
			var user = response.data[i];
			user.pic = "https://graph.facebook.com/" + user.id + "/picture?type=square";
			users[i] = user;
		}
		_facebookLookup(users);
	});
}
function _facebookLookup(users){
    $('#facebookDivUsers').html("");
    if(users.length == 0) {
   	 alertError("No matching contact found on Facebook.");
   	 return false;
    }
    for (var i = 0; i < users.length; i++) {
   	 var div = document.createElement("DIV");
   	 div.setAttribute("id", users[i]["id"]);
   	 div.className = "facebookUser";
   
   	 var img = document.createElement("IMG");
   	 var pic = users[i]["pic"];
   	 if (!pic) {
   		 pic = "images/facebook_placeholder.gif";
   	 }
   	 img.src = pic;
   	 img.setAttribute("width", "50px");
   	 img.setAttribute("height", "50px");
   	 div.appendChild(img);
   
   	 var titleDiv = document.createElement("DIV");
   	 titleDiv.innerHTML = users[i]["name"];
   	 div.appendChild(titleDiv);
   	 $(div).click(function(e) {
   		 $('#memberPanel_facebook_id').val(this.getAttribute("id"));
   		 $('#facebookDiv').css('display',  "none");
   	 });
   	 $('#facebookDivUsers').append(div);
    }
    $('#facebookDiv').show();
}


function facebookPageVerify() {
	if(!FB) {
		alertError("You're not logged into Facebook.");
		return;
	}
	
	var facebook_id = $('#memberPanel_facebook_id').val();
    if(facebook_id == 0) {
      	 alertError("You must specify a Facebook ID. Try using lookup first.");
      	 return false;
    }
    
    
    FB.api('/me/accounts', function(response) {

    	var batch = [];
    	 for(var i = 0; i < response.data.length; i++) {
    		 var page = response.data[i];
    		 
    		 batch[batch.length] = {
    			"method": "GET",
    			"relative_url": facebook_id + "/likes/" + page.id
    		 };
    	 }
    	 
		 FB.api('/' + facebook_id + "/likes/" + page.id, "POST", {
			 'access_token': page.access_token,
			 'batch': batch
			 }, function(like_response) {
				 
		     var pages = [];
			 for(var i = 0; i < like_response.length; i++) {
				 var response = like_response[i];
				 var data = jQuery.parseJSON(response['body']);
				 if(data.data && data.data.length == 1) {
					 pages[pages.length] = data.data[0];
				 }
			 }
			 _facebookPageVerify(pages);
		 });    	 
    });
}

function _facebookPageVerify(status){
	
     $('#facebookPageDivPages').html("");
     if(!status.length) {
    	 alertError("No matching contact found on FaceBook or not a fan of any pages.");
    	 return false;
     }
     for ( var i = 0; i < status.length; i++) {
    	 // id, name, isFan
    	 var div = document.createElement("DIV");
    	 div.setAttribute("id", status[i]["id"]);
    	 div.className = "facebookPage";
    
    	 var titleDiv = document.createElement("DIV");
    	 titleDiv.innerHTML = "<a target='_new' href='http://www.facebook.com/profile.php?id="
    		+ status[i]["id"]
    	 	+ "'>"
    	 	+ status[i]["name"] + "</a>";
    	 div.appendChild(titleDiv);
    	 $('#facebookPageDivPages').append(div);
     }
     $('#facebookPageDiv').show();
}

function bitlyResponse(transport){
    alertMessage(transport.responseText);
}

function _insertUrl(json){
	var response = jQuery.parseJSON(json['response']);
	var textarea = json["textarea"];
     if (json && json.errorCode == 1) {
    	 alertMessage(json.errorMessage);
    	 return;
     }
     var t = $('#' + textarea);
     var value = t.val();
     for ( var key in response.results) {
    	 value += " " + response.results[key].shortUrl;
     }
     t.val(value);
     updateTwitterChars();
}

function insertUrl(action, textarea, uid){
     showForcefield();
     var service = "statusupdate.service";
     var params = {
    	'action': action,
    	'uid': uid,
    	'textarea': textarea
     };
     ajaxButtonRequest(service, params, _insertUrl, logit);
}

function updateTwitterChars(){
	$('#twitterChars').removeClass("twitterCharsError");
	
    var length = $('#twitterStatusUpdate').val().length;
    $('#twitterChars').html(160 - length);
    $('#twitterChars').addClass("twitterChars");
    if (160 - length < 0) {
      $('#twitterChars').addClass("twitterCharsError");
    }
}

function updateCartButtons(){
	var checkoutButton = $('#checkout_button');
	if (checkoutButton.html() == "<span class=\"ui-button-text\"><img src=\"images/cart_edit.gif\" />Update Cart</span>") {
		return;
	}
	$('#passcode_button').hide('slow');
	checkoutButton.html("<span class=\"ui-button-text\"><img src=\"images/cart_edit.gif\" />Update Cart</span>");
	checkoutButton.attr("onclick", "");
	checkoutButton.bind('click', function() {
		setAction($('#shopping_cart_form'), 'updateCart');
		return true;
	});
	return false;
}

function highlight(el){
	var destination = $(el).offset().top;
	$('html, body').animate({
        scrollTop: destination
    }, 'slow');	
    $(el).effect('pulsate', {
        times: 3
    }, 1000);
    return false;
}

function gotoTop(){
    $('html, body').animate({
        scrollTop: 0
    }, 'slow');
    return false;
}

function setAction(form, action){
    form.find("input[name='action']").val(action);
    
}

function addLocation(formId){
    var form = document.getElementById(formId);
    setAction($('#' + formId), "addLocation");
    
    if (!$('#locationModal_owner_uid').val()) {
        $('#locationModal_owner_uid').val($('#step2_producer_uid').val());
    }
    if (!validate(form)) {
        return false;
    }
    ajaxButtonClick("addproduction.service", formId, _addLocation);
    return false;
}

function _addLocation(data){
    if (data.responseCode == "500") {
        alertMessage(data.responseObj);
        return false;
    }
    
    logit('#step2_locationUid option[value=\'' + data.responseObj.fields.UID + '\']');
    logit($('#step2_locationUid option[value=\'' + data.responseObj.fields.UID + '\']'));
    if($('#step2_locationUid option[value=\'' + data.responseObj.fields.UID + '\']').length == 0) {
    	$('<option></option>').attr("value", data.responseObj.fields.UID).text(data.responseObj.fields.NAME).attr("selected", "selected").appendTo($('#step2_locationUid'));
	}
    $('#step2_locationUid').show();
    $(data.modalId).dialog('close');
    alertMessage(data.responseObj.fields.NAME + ' was saved.');
    return false;
}
function updateLocationTitle(formId) {
	var title = $('#' + formId.replace("_form", "")).dialog( "option", "title" );
	
    var button = $('#createLocationModal_updateButton span.ui-button-text');
    var html = button.html();
    logit(title);
    if(title.length > 0 && title.match(/Edit.*/)) {
	    html = html.replace("add", "edit");
	    html = html.replace("Add", "Edit");
	    button.html(html);
    } else {
	    html = html.replace("edit", "add");
	    html = html.replace("Edit", "Add");
	    button.html(html);
    }
}
function clearLocation(formId) {
	clearModal(formId);
	updateLocationTitle(formId);
	
	var form = $('#' + formId);
}
function populateLocation(formId){
	
	clearModal(formId);
	updateLocationTitle(formId);
	
    var form = $('#' + formId);
    var locationUID = $('#step2_locationUid').val()
    if (locationUID) {
        $('#locationModal_uid').val(locationUID);
        setAction(form, "populateLocation");
        ajaxButtonClick("addproduction.service", formId, _populateLocation);
    }
    return false;
}

function _populateLocation(data){
    if (data.responseCode == "500") {
        alertMessage(data.responseObj);
        return false;
    }
    var fields = data.responseObj.fields;
    for (key in fields) {
        if ($('#locationModal_' + key.toLowerCase()).length > 0) {
            $('#locationModal_' + key.toLowerCase()).val(fields[key]);
        }
    }
    return false;
}

function getQueryParams(url) {
	var a =  document.createElement('a');
    a.href = url;
    
    var params = {};
    var pairs = a.search.replace(/^\?/,'').split('&');
    for(var index in pairs) {
    	var pair = pairs[index];
    	var entry = pair.split('=');
    	params[entry[0]] = entry[1];
    }
    return params;
}

var loading = false;
function filterTable(service, tablePrefix) {
	var table = $("#" + tablePrefix + "_tbody");
	table.html("");
	pagesLoaded = {};
	loadTable(service, tablePrefix, 1);
}
function addQuery(table, name, value) {
	var query = $("#" + table + "_tbody").data("query");
	if(!query) {
		query = {};
	}
	query[name] = value;
	$("#" + table + "_tbody").data("query", query);
}
function clearQuery(table) {
	$("#" + table + "_tbody").data("query", {});
}
function loadTable(service, tablePrefix, page, callback) {
	// prevent too much loading at once
	
	var table = $("#" + tablePrefix + "_tbody");
	if(loading == true) {
		logit("loading");
		return;
	}
	
	logit("loading page " + page);
	loading = true;
	
	var data = {
			table: table.attr('id'),
			action: 'populateTable',
			p: page
		};
	var query = $(table).data("query");
	for(var key in query) {
		data[key] = query[key];
	}
	
	return ajaxButtonRequest(service, $.param(data, true), function(data) {
		_loadTable(table, data);
		if(callback) {
			callback.call(this, true);
		} else {
			clearForcefield();
		}
	}, logit, true);	
}
function _loadTable(table, data) {
	table.html("");
	table.append(data);
	loading = false;
}

var lastChar = -1;
function scrollODex(service, tablePrefix, scrollable, el) {
	
	
	var firstChar = $(el).html().charCodeAt(0);
	
	if(lastChar == firstChar || lastChar == firstChar + 1) {
		firstChar = lastChar + 1;
	}
	lastChar = firstChar;
	
	var lookupChar = String.fromCharCode(lastChar);
	logit(lookupChar);
	var table = $("#" + tablePrefix + "_tbody");
	var data = {
			table: table.attr('id'),
			action: 'populateTable',
			c: lookupChar
	};
	var query = $(table).data("query");
	for(var key in query) {
		data[key] = query[key];
	}
	ajaxButtonRequest(service, $.param(data, true), function(data) {
		_loadTable(table, data);
		clearForcefield();
	}, logit, true);	
}
function xferProductionData(showEditor, service, action) {
	var production = {};
	production.action = action;
	production.layout = $('#layout').val();
	production.uid = $('#step2_uid').val();
	production.producer_uid = $('#step2_producer_uid').val();
	production.name = $('#step2_name').val();
	production.email = $('#step2_email').val();
	production.link = $('#step2_link').val();
	production.locationUid = $('#step2_locationUid').val();
	production.service_charge = $('#step2_service_charge').val();
	production.shows = showEditor.serialize();
	
	production.descriptions = [];
	$('#descriptionFields').find("textarea").each(function() {
		var description = $(this);
		production.descriptions[production.descriptions.length] = {
			'content': description.val(),
			'date': description.attr('date'),
			'time': description.attr('time')
		};
	});
	
	production.email_subject = $('#step5_response_email_subject').val();
	production.email_body = $('#step5_response_email_body').val();
	production.matte_color = $('#step6_matte_color').val();
	production.panel_color = $('#step6_panel_color').val();
	production.text_color = $('#step6_text_color').val();
	production.link_color = $('#step6_link_color').val();
	production.panel_font = $('#step6_panel_font').val();
	production.panel_font_size = $('#step6_panel_font_size').val();
	production.extra_css = $('#step6_extra_css').val();

	ajaxButtonRequest(service, production, _xferProductionData);
}
function _xferProductionData(data) {
	if(data.responseObj && data.responseObj.redirect) {
		document.location = basepath + data.responseObj.redirect;
		return;
	}
	alertError(data);
}
function getNiceDate(date){
    var months = new Array("Jan", "Feb", "Mar", 
    		"Apr", "May", "Jun", "Jul", "Aug", "Sep", 
    		"Oct", "Nov", "Dec");
    var currentDate = new Date(date.substring(0, 4), Number(date.substring(5,7)) - 1, date.substring(8,10));
    return months[currentDate.getMonth()] + ' ' + currentDate.getDate();	
};
function saveStyleToSession(url) {
	var params = {
			'url': url,
			'action': 'saveStyleToSession',
			'styleTab_matte_color': $('#styleTab_matte_color').val(),
			'styleTab_panel_color': $('#styleTab_panel_color').val(),
			'styleTab_panel_font': $('#styleTab_panel_font').val(),
			'styleTab_panel_font_size': $('#styleTab_panel_font_size').val(),
			'styleTab_text_color': $('#styleTab_text_color').val(),
			'styleTab_link_color': $('#styleTab_link_color').val(),
			'styleTab_extra_css': $('#styleTab_extra_css').val()
	};
	ajaxButtonRequest('calendarsettings.service', params, _saveStyleToSession, logit);
}
function _saveStyleToSession(json) {
	logit("Opening " + json.responseObj);
	window.open(json.responseObj);
}
function switchIntroTab(tabName) {
	$('div.ui-buttonset').find('label').removeClass('ui-state-active');
	
	$('div.introTab:visible').hide('blind', {}, 'fast', function() {
		$(tabName).show('blind', {}, 'fast');
		$(tabName + '_label').addClass('ui-state-active');
	}); 
	return false;
}
function changeSlide() {
	var slides = $('div.slide');
	var currentIndex = 0;
	for(var i = 0, il = slides.length; i < il; i++) {
		if($(slides[i]).is(':visible')) {
			currentIndex = i + 1;
			if(currentIndex >= slides.length) {
				currentIndex = 0;
			}
		}
	}
	$('div.slide:visible').hide('blind', {}, 'slow', function() {
		$('div.slide:eq(' + currentIndex + ')').show('blind', {}, 'slow');
		window.setTimeout(changeSlide, 10000);
	});
}
function _disconnectFacebook(data) {
	document.location = 'usersettings.html#tabs-2';
}
function fixTransaction(provider_key) {
	ajaxButtonClick('missing.service', 'fixTransactionModal_form', _fixTransaction, _fixTransaction);
	return false;
}
function _fixTransaction(data) {
	alertMessage(data['responseObj'], function() { $('#missingreport_form').submit()});
}
function populateTransaction(provider_key) {
	setAction($('#fixTransactionModal_form'), "fixTransaction");
	$('#billing_ref1').val('');
	$('#billing_ref2').val('');
	$('#provider_key').val(provider_key);
}
function apiCall(button, service, requestType, success) {
    var forms = $(button).parents("form");
    var form = forms[0];
    if(!form.onsubmit()) {
        return false;
    }
    var prefix = form.id.replace('_form','');
    
    var data = $(form).serializeArray();
    for(index in data) {
    	el = data[index];
    	el.name = el.name.replace(prefix + '_', '');
    }
    ajaxButtonRequest('api/1.0/' + service + "?api_key=" + api_key, data, success, _apiError, false, requestType);
    return false;
}
function _apiError(output) {
    alertError(output['response']);
}
function manualCode() {
	promptMessage('Apply Discount Code', '<div id="useCodeDialog"><label for="code">Apply Code</label><input id="code" name="code" /></div>', function(dialog) {
		var code = $('#code').val()
		if(code.length == 0) {
			$('#useCodeDialog').append($('<div class="dialogError">You must specify a code.</div>'));
			return false;
		}
		ajaxButtonRequest("editreservation.service", {
			'action': 'validateCode', 
			'editreservation_show_uid': $('#editreservation_show_uid').val(),
			'editreservation_quantity': $('#editreservation_quantity').val(),
			'editreservation_code': code
		}, function(data) {
			if(data.responseCode == 500) {
				clearForcefield(data);
				alertError(data.responseObj);
				return;
			}
			logit(data);
			// here we need to update the page to have the using code div
			// with a hidden code input
			/*
			overrideSelect('editreservation_price', data.responseObj.price);
			if(data.responseObj.comp == 'True') {
				$('#editreservation_paid').val('C');
			}
			*/
			
			var code = data.responseObj.code;
			var uid = data.responseObj.uid;
			$('#editreservation_code').val(uid);
			$('#discount_code_div').html($('<div class="form-static">Using discount code: <a href="edit_discount_code.html?discount_code_uid=' + uid + '">' + code + '</a></div>'))
			clearForcefield();
		}, function(data) {
			clearForcefield(data);
			alertError("Error applying code.");
		}, true);
		return true;
	});
	return false;
	
}
function useCode() {
	promptMessage('Apply Discount Code', '<div id="useCodeDialog"><label for="code">Apply Code</label><input id="code" name="code" /></div>', function(dialog) {
		var code = $('#code').val()
		if(code.length == 0) {
			$('#useCodeDialog').append($('<div class="dialogError">You must specify a code.</div>'));
			return false;
		}
		ajaxButtonRequest("editcart.service", {action: 'useCode', code: code}, function(data) {
			if(data.responseCode == 500) {
				clearForcefield(data);
				alertError(data.responseObj);
				return;
			}
			logit(data);
			setAction($('#shopping_cart_form'), "reload");
			$('#shopping_cart_form').submit();
		}, function(data) {
			clearForcefield(data);
			alertError("Error applying code.");
		}, true);
		return true;
	});
	return false;
}
function stripeResponseHandler(status, response) {
	if(status != 200) {
		$('.submit-button').attr("disabled", "");
		clearForcefield();
		
		if(!response || !response.error || !response.error.message) {
			alertError("Unknown error.");
			return false;
		}
		alertError(response.error.message);
		return false;
	}
	$('#stripe_token').val(response.id);
	$('#payment_form').get(0).submit();
}
function pwycValidator(id, val, overrideLabel) {
	if(isEmpty(val)) {
		logit("empty");
		return false;
	}
	val = String(val).replace(/(\$)/, "").replace(/(\s+)/g,"");
	if(!val.match(/\d+\.?\d?\d?/)) {
		alert("You must enter a numeric price.");
		return false;
	}
	
    if(isEmpty(overrideLabel)) {
    	overrideLabel = " Override";
    }
	val = formatMoney(val);
	var select = document.getElementById(id); 
    select.options[select.options.length] = new Option(val + " (" + overrideLabel + ")", 'custom');
    select.options[select.options.length - 1].selected = true;
    document.getElementById(String(id).replace(/select/,'custom')).value = val;
    return false;
}

