function displaydate(dom, val, argstr) {
	var date = new Date(val);
	if(isNaN(date.getFullYear()))
		return val;
	
	return lfjs.displayDate(new Date(val), "%Y-%m-%d");
}


var specialsfieldlist = [
	{ xml: "title", dom: "special_title" },
	{ xml: "reqnotify", dom: "special_reqnotify" },
	{ xml: "description", dom: "special_description" },
	{ xml: "targetname", dom: "special_targetname" },
	{ xml: "brochurecost", dom: "special_brochurecost" },
	{ xml: "cost", dom: "special_cost" },
	{ xml: "startdate", dom: "special_startdate", showVal: displaydate },
	{ xml: "enddate", dom: "special_enddate", showVal: displaydate },
	{ xml: "speccatkey", dom: "special_speccat" },
	{ xml: "speckey", dom: "specialkey" },
	{ xml: "targetkey", dom: "targetid" }
]

modules.specials = {
	sellername: '',
	sellEmail: '',
	views: {
		managespecials: { title: "Specials", headers: "managespecials" },
		managespecial: { title: "Manage Special", headers: "specialinfo" },
		newspecial: { title: "Add New Special", headers: "specialinfo" }
	},
	init: function() {
		modules.specials.sellername = document.cookie.replace(/^.*sellerresauth=([^;]+).*$/,'$1').split(/\|/)[1];
		//load the list of sellers into the special request notify select list
		$.ajax({ url: "manageaccount.cfc?method=getsellers",
			   	cache: false,
				success: function(req) {
					var sel = $("#special_reqnotify")[0];
					sel.options.length = 0;
					sel.options[0] = new Option("None","");
					
					var agencyemail = $(req).find("agencyemail:first").text();
					if(agencyemail != "") {
						sel.options[sel.options.length] = new Option($(req).find("agencyname:first").text() + " (" + agencyemail + ")", agencyemail);
					}
					$(req).find("seller").each(function(i) {
						var agentname = $(this).find("agentname:first").text();
						var loginname = $(this).find("loginname:first").text();
						var email = $(this).find("email:first").text();
						if(email != "") {
							if(agentname == "")
								agentname = loginname;
							if (modules.specials.sellername == loginname) {
								modules.specials.sellEmail = email;
							}
							sel.options[sel.options.length] = new Option(agentname + " (" + email + ")", email);
						}
						
					});
					sel = null;
				}, 
				error: function() {
					
					var sel = $("#special_reqnotify")[0];
					sel.options.length = 0;
					sel.options[0] = new Option("None","");
				}
			} );
	},
	//FocusSearch functions
	set_target: function() {
		var fswin = window.open("/focussearch", "focussearch", "resizable,height=665,width=782,scrollbars");
		fswin.focus();
		fscallback = modules.specials.fsSpecialButtons;
	},
	fsSpecialButtons: function() {
		return [ 
					{ title:"Select Resort", clickfunc: modules.specials.fsSpecialSelect } ];
	},

	fsSpecialSelect: function(which){
		modules.specials.update_target(which);
		return true;
	},
	update_target: function (which){
		var targetkey = which;
		$.ajax( {
			type: "POST",
			url: "managespecial.cfc?method=gettargetdetails&targetkey="+targetkey,
			async: false,
			cache: false,
			complete: function(req) {
				$("#special_targetname").text($(req.responseXML).find("targetname:first").text());
				$("#targetid").val(targetkey);
				$("select[name^='specialscustom_grp']").each(function(i) {
					this.options.length = 0;
					this.options[0] = new Option("Any","");
					var findnode = this.name.replace(/^specialscustom_grp(.*)$/, "$1");
					var sel = this;
					$(req.responseXML).find(findnode).each(function(i) {
						var name = $(this).find("name:first").text();
						var val =  $(this).find("detailkey:first").text();
						
						sel.options[sel.options.length] = new Option(name, val);
					});
					sel = null;
				});
				
			}
			
		} );
	},
	//end FocusSearch functions
	
	sortgrid: function(id, index, colname, thobj, griddiv) {
		
		var view = griddiv.currview;
		griddiv.setData([]);
		var url = griddiv.lasturl;
		var sortfield = id;
		if(griddiv.lastsort) {
			if(griddiv.lastsort.indexOf(sortfield) == 0 && !/desc$/i.test(griddiv.lastsort))
				sortfield += " desc";
		} 
		url += "&orderby=" + sortfield;
		griddiv.lastsort = sortfield;;
		modules.specials.showspecials(view, url);
	},
	showspecials: function(view, url){
		if(typeof view == "undefined")
			view = "managespecials";
		
		$("#overviewspecial")[0].activate({
			title:"Specials", 
			keyhandler: modules.specials.manage_specials_keyhandler
		});
		var speclist = $('#speclist')[0];
		speclist.currview = view;
		speclist.empty();
		if(modules.specials.listcolumns && modules.specials.listcolumns[modules.specials.views[view].headers]) {
			var headers = modules.specials.listcolumns[modules.specials.views[view].headers];
			
			var setheaders = new Array();
			var setwidths = new Array();
			
			for (var i=0; i < headers.length; i++) {
				var title = "Click to sort by " + headers[i].label
				setheaders[i] = { name: headers[i].label, id: headers[i].alias, onclick: modules.specials.sortgrid, title: title };
				if(headers[i].width)
					setwidths[i] = headers[i].width;
				else
					setwidths[i] = "";
			}
			speclist.setHeaders(setheaders);
			speclist.setColWidths(setwidths);
		} else {
			speclist.setHeaders([{name:"Name"},{name:"Category"}, {name:"Expiration"}]);
			$('#speclist')[0].setColWidths(["60%","25%","15%"]);
		}
		
		var currview = view;
		
		if(!url) {
			var url = "managespecial.cfc?method=list";
			//cache the url for use in sorting
			$('#speclist')[0].lasturl = url;
		}
		$.ajax( { type: "GET", 
				url: url,
				cache: false,
				complete: function(req) { modules.specials.listloading(req, currview); }
			} );
	},
	
	closeoverview: function(){
		$("#overviewspecial")[0].deactivate();
		$('#speclist')[0].currview = "";
		$('#speclist')[0].lasturl = "";
	},
	
	manage_specials_keyhandler: function(in_key) {
	   switch (in_key.toLowerCase()) {
		case 'down':
			$('#speclist')[0].selectNext();
			return false;
		case 'up':
			$('#speclist')[0].selectNext(-1);
			return false;
		case 'esc':
			$('#overviewspecial')[0].deactivate();
			$('#speclist')[0].currview = "";
			$('#speclist')[0].lasturl = "";
			return false;
		case 'enter':
			if($('#speclist')[0].getSelectedId())
				modules.specials.manage_special($('#speclist')[0].getSelectedId(), "managespecial");
			return false;
		default:
			return true;
	   }
	},
	
	

	listloading: function(req, view) {
		var currview = view;
		var xml = $(req.responseXML);
		$('#speclist')[0].setData(xml.find("special"),
				{ append: true, 
					insfunc:  function(grid, row, which) { modules.specials.listloadadd(grid, row, which, currview) },
					donefunc: modules.specials.listloaddone });
	},

	listloadadd: function(grid, rows, which, view) {
		
		var data = [];
		var fields = modules.specials.listcolumns[modules.specials.views[view].headers];
		for(var i=0; i < fields.length; i++) {
			if($(rows[which]).find(fields[i].alias).length) {
				var val = $(rows[which]).find(fields[i].alias + ":first").text();
				if(fields[i].fieldtype == "date") {
					val = lfjs.displayDate(new Date(val));
				} 
				if(val == "")
					val = "&nbsp;";
				data[data.length] = val;
			}
		}
		grid.addRow($(rows[which]).find("speckey:first").text(), data,
				{ ondblclick:function(){ lfjs.keypress.stuff('enter')}});
	
	},

	listloaddone: function(grid) {

	},
	
	add_special: function(){
		modules.specials.manage_special(0,"newspecial");
	},
	
	manage_special: function (which, view) {
		var win = $('#managespecial')[0];
		
		$("#specialerror").html("").hide();
	
		Date.format = 'yyyy-mm-dd';
		var now = new Date();
		$('.date-pick').datePicker().dpSetDisplayedMonth(now.getMonth(), now.getFullYear()).each(function() {
			var sel = $(this).dpGetSelected();
			if(sel && sel.length) {
				for(var i=0; i < sel.length; i++) 
					$(this).dpSetSelected(lfjs.displayDate(new Date(sel[i]), "%Y-%m-%d"), false, false);
			}
		});
		
		win.dbform = new lfjs.dbForm(specialsfieldlist);			// Clear fields
		if (which) {
			$('#managespecial :input').attr("disabled", true).css( {"backgroundColor": "white", color: "black"});
			$("#closespecial").show().attr("disabled", false);
			$("#cancelspecial").val("Close Window").attr("disabled", false);
			$("#savespecial").hide();
			$('.date-pick').dpSetDisabled(true);
			// Load special
			$.ajax( { type: "GET", 
					cache: false,
					url: "managespecial.cfc?method=get&speckey=" + which,
					complete: modules.specials.specialloaded} );
		} else {
			$('#managespecial :input').attr("disabled", false);
			$("#closespecial").hide();	
			$("#savespecial").show();
			$("#cancelspecial").val("Discard Changes");
			$('.date-pick').dpSetDisabled(false);
			$("select[name^='specialscustom_grp']").each(function(i) {
				this.options.length = 0;
				this.options[0] = new Option("Any","");
			});
			$("#special_speccat")[0].selectedIndex = 0;
			$("#special_reqnotify option[value='" + modules.specials.sellEmail + "']")[0].selected = true;    //.val(modules.specials.sellEmail);
		}
		
		$('#managespecial')[0].activate({
			title:modules.specials.views[view].title, 
			keyhandler:modules.specials.manage_special_keyhandler});
	},
	specialloaded: function(req) {
		var req = req;
		
		$("select[name^='specialscustom_grp']").each(function(i) {
			this.options.length = 0;
			this.options[0] = new Option("Any","");
			var findnode = this.name.replace(/^specialscustom_grp(.*)$/, "$1");
			var sel = this;
			
			$(req.responseXML).find(findnode + "s:first").find(findnode).each(function(i) {
				var name = $(this).find("name:first").text();
				var val =  $(this).find("detailkey:first").text();
				
				sel.options[sel.options.length] = new Option(name, val);
			});
			sel = null;
		});
		
		$('#managespecial')[0].dbform =
					new lfjs.dbForm(specialsfieldlist, $(req.responseXML).find("special")[0]);
	},
	manage_special_keyhandler: function(in_key) {
		switch (in_key.toLowerCase()) {
			case 'pgdn':
			case 'pgup':
				if ($('#managespecial')[0].dbform.hasChanges()){
					var returnval = confirm("Do you wish to save your changes?", "");
					if (returnval){
						modules.specials.save_special();	
					}
				}
				$('#managespecial')[0].deactivate();
				$('#speclist')[0].selectNext(
						in_key.toLowerCase() == 'pgdn' ? 1 : -1 );
				lfjs.keypress.stuff('enter');
				return false;
			case 'ctrl+enter':
				modules.specials.save_special();
				//$('#managespecial')[0].deactivate();
				return false;
			case 'esc':
				$('#managespecial')[0].deactivate();
				return false;
		
		}
		return true;
	},
	delete_special: function() {
		var val = $("#managespecial #specialkey").val();
		if(val != "") {
			if (confirm("Delete this special?")){
				var thisrowid =  $('#speclist')[0].getSelectedId();
				$.ajax( {type: "GET", 
					   	cache: false,
						url: "managespecial.cfc?method=delete&speckey=" +val,
						complete: function(req){
							if($(req.responseXML).find("status").length) {
								 $('#speclist')[0].removeRow(val);
								 $('#managespecial')[0].deactivate();
							}
						}
				} );	
			}
		}
	},
	save_special: function() {
		
		$("#bookerror").slideUp("fast");
		if($('#speclist')[0].currview)
			var currview = $('#speclist')[0].currview;
		else
			var currview = "managespecials";
		var err = modules.specials.check_required();
		if(err.length)
			err = ["All required fields must be filled out."];
			
		
		var currencyerror = false;
		$("#managespecial input[name$='cost']").each(function(i){
				//validate currency
				if(!/^\$?\d{1,3}(,?\d{3})*(\.\d{1,2})?$/.test($(this).val()) && $(this).val() != "")
					currencyerror = true;
		});
		if($("#special_targetname").text() == "") {
			err[err.length] = "A " + application.instancename.toLowerCase() + " must be selected by clicking on the \"Search for " + application.instancename + "\" button.";	
		}
		if(currencyerror) {
			err[err.length] = "All costs must be in a valid currency format (i.e. 850.99).";
		}
		if(err.length) {
			$("#specialerror").html(err.join("<br>")).slideDown("normal");
			return;
		}
		lfjs.window.wait();
		$("#specialerror").slideUp("normal");
		var changedval = $('#managespecial')[0].dbform.gather({domprefix: "special_"});
		//var speckey = $('#speclist')[0].getSelectedId();
		//changedval["speckey"]=speckey; 
		
		$.ajax({
			   type: "POST",
			   url: "managespecial.cfc?method=save",
			   data: changedval,
			   cache: false,
			   success: function(req){
				   lfjs.window.nowait();
					if($(req).find("error").length) {
						var errors = [];
						$(req).find("error").each(function(i) {
							errors[errors.length] = $(this).text();							   
						});
						$("#specialerror").html(errors.join("<br>")).slideDown("normal");
					} else {
						//request returns the special info, to populate the selectgrid, so use existence as confirmation
						if($(req).find("special").length) {
							modules.specials.listloadadd($('#speclist')[0], $(req).find("special:first"), 0, currview);
							$('#speclist')[0].selectRow($(req).find("speckey:first").text());
							lfjs.keypress.stuff("esc");
						} else if($(req).find("status").length && $(req).find("status").text().toLowerCase() == "success") {
							lfjs.keypress.stuff("esc");
						} else {
							$("#specialerror").html("There was a problem saving your special.<br>Please submit your special again").slideDown("normal");
						}
					}
			   	},
				error: function(req, err) {
				   lfjs.window.nowait();
					$("#specialerror").html("Error: " + err).slideDown("normal");
				}
		});
	},
	getRangeVal: function(domid, val) {
		
		if (val.indexOf('|') < 0)
			return val;
		else if (domid.indexOf("start") >= 0)
			return val.substr(0, val.indexOf('|'));
		else
			return val.substr(val.indexOf('|')+1);
	},
	
	displaydate: function(dom, val, argstr) {
		return lfjs.displayDate(new Date(val), "%Y-%m-%d");
	},

// Requires fieldlist and specfields to be defined in the instance-specfic
//    version of this file
	specialLoaded: function(resp) {
		for (var i=0; i < fieldlist.length; i++) {
			var val = resp.children(fieldlist[i].xml).text();
			if (fieldlist[i].loadVal){
				val = fieldlist[i].loadVal(fieldlist[i].dom, val);}
			var dom = $('#' + fieldlist[i].dom)[0];
			switch (dom.nodeName.toLowerCase()) {
				case "select":
					lfjs.setSelectedIndex(dom, val);
					break;
				case "input":
				case "textarea":
					dom.value = val;
					break;
				default:
					$(dom).text(val);
					break;
			}
		}
		return true;
	},
	
	check_required: function() {
		var errors = [];
		$("#managespecial .required").each(function() {
			if($(this).val() == "" && $(this).text() == "")
				errors[errors.length] = this.name;
		})
		return errors;
	}
	
	
}
