
dojo.require("dijit.layout.LinkPane");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.form.FilteringSelect");
dojo.require("dijit.form.Form");
dojo.require("dijit.form.ValidationTextBox");
dojo.require("dijit.form.CheckBox");
dojo.require("dijit.form.NumberTextBox");
//dojo.require("dijit.form.Textarea");
dojo.require("dojo.currency");
dojo.require("dojox.image.Lightbox");

var stateStoreData = {
	identifier: 'abbr',
	label: 'name',
	items: [{abbr: 'AL',name: 'Alabama'}, {abbr: 'AK',name: 'Alaska'},
		{abbr: 'AZ',name: 'Arizona'}, {abbr: 'AR',name: 'Arkansas'},
		{abbr: 'CA',name: 'California'},{abbr: 'CO',name: 'Colorado'},
		{abbr: 'CT',name: 'Connecticut'},
		{abbr: 'DE',name: 'Delaware'},{abbr: 'DC',name: 'Washington DC'},
		{abbr: 'FL',name: 'Florida'},{abbr: 'GA',name: 'Georgia'},
		{abbr: 'HI',name: 'Hawaii'},{abbr: 'ID',name: 'Idaho'},
		{abbr: 'IL',name: 'Illinois'},{abbr: 'IN',name: 'Indiana'},
		{abbr: 'IA',name: 'Iowa'},{abbr: 'KS',name: 'Kansas'},
		{abbr: 'KY',name: 'Kentucky'},{abbr: 'LA',name: 'Louisiana'},
		{abbr: 'ME',name: 'Maine'}, {abbr: 'MD',name: 'Maryland'},
		{abbr: 'MA',name: 'Massachusetts'},{abbr: 'MI',name: 'Michigan'},
		{abbr: 'MN',name: 'Minnesota'},{abbr: 'MS',name: 'Mississisppi'},
		{abbr: 'MO',name: 'Missouri'},{abbr: 'MT',name: 'Montana'},
		{abbr: 'NE',name: 'Nebraska'},{abbr: 'NV',name: 'Nevada'},
		{abbr: 'NH',name: 'New Hampshire'},{abbr: 'NJ',name: 'New Jersey'},
		{abbr: 'NM',name: 'New Mexico'},{abbr: 'NY',name: 'New York'},
		{abbr: 'NC',name: 'North Carolina'},{abbr: 'ND',name: 'North Dakota'},
		{abbr: 'OH',name: 'Ohio'},{abbr: 'OK',name: 'Oklahoma'},
		{abbr: 'OR',name: 'Oregon'}, {abbr: 'PA',name: 'Pennsylvania'},
		{abbr: 'RI',name: 'Rhode Island'},{abbr: 'SC',name: 'South Carolina'},
		{abbr: 'SD',name: 'South Dakota'},{abbr: 'TN',name: 'Tennessee'},
		{abbr: 'TX',name: 'Texas'},{abbr: 'UT',name: 'Utah'},
		{abbr: 'VT',name: 'Vermont'},{abbr: 'VA',name: 'Virginia'},
		{abbr: 'WA',name: 'Washington'},{abbr: 'WV',name: 'West Virginia'},
		{abbr: 'WI',name: 'Wisconsin'},{abbr: 'WY',name: 'Wyoming'}
	]
};
var uri = window.location.href;
console.log("URI: " + uri);
var query = uri.substring(uri.indexOf("?") + 1, uri.length);
console.log("QUERY: " + query);
var queryObject = dojo.queryToObject(query);
console.debug("queryObj: ",  queryObject);
dojo.addOnLoad(function() {
	console.log("in onload");
        if(queryObject.response == "thanks")
            {
                var content = "<h4 style='margin-top:0px; padding:5px;'>Thank you for purchasing from Birdie Publishing! Your receipt from Paypal will arrive shortly.<br>If you have any questions " + 
                "or concerns please contact <a href='mailto:payments@birdiepublishing.com'>payments@birdiepublishing.com</a>.</h4>";
                dojo.byId("paypalResponseText").innerHTML = content;
            }
       if(queryObject.response == "cancel")
            {
                var content = "<h4 style='margin-top:0px; padding:5px;'>Your payment with Paypal has been cancelled. However, we have your listing stored in our database - should you wish" +
                    " to still be listed with us, please email us at <a href='mailto:getlisted@birdiepublishing.com'>getlisted@birdiepublishing.com</a> " +
                    "and we will finish processing your payment to get listed in The Thrifty Traveller!</h4>";
                dojo.byId("paypalResponseText").innerHTML = content;
            }
	sendMail = function(emailContent) {
		dojo.xhrPost({
                    url: "sendmail.php",
                    content: emailContent,
                    load: function(response) {
						if(response.success) {
							console.log("email sent");
							return true;
						}
						else {
							console.log("email failed!!1");
							return false;
						}
					},
                    error: function() { console.log("email failed!!2"); return false;}
                });
		
	}
	
	animateChange = function(currentDiv,divName)
	{
			var wipeOut = dojo.fx.wipeOut({node: currentDiv});
			var wipeIn = dojo.fx.wipeIn({node: divName});
			var currentAnimation = dojo.fx.chain([wipeOut, wipeIn]);
			
			currentAnimation.play();	
	};
	
	function stripslashes (str) {
  
    // *     example 1: stripslashes('Kevin\'s code');
    // *     returns 1: "Kevin's code"
    // *     example 2: stripslashes('Kevin\\\'s code');
    // *     returns 2: "Kevin\'s code"
    return (str + '').replace(/\\(.?)/g, function (s, n1) {
        switch (n1) {
        case '\\':
            return '\\';
        case '0':
            return '\u0000';
        case '':
            return '';
        default:
            return n1;
        }
    });
}
	
	
	/*********************************************************************/
	/***********************Get Listed************************************/
	/*********************************************************************/
	cpListed = dijit.byId("listed");	
	cpListed.onLoad = function(){
		console.debug("cplisted loaded");
		
		dojo.connect(listForm, "onSubmit", function(event) {
			
			console.log("save button clicked");
			event.preventDefault();
			event.stopPropagation();
			if (listForm.validate())
			{
				console.debug("listform",listForm);
				var xhrArgs = {
					form: listForm.domNode,
					handleAs: "text",
					load: function(json) {
						data = dojo.fromJson(json);
						console.debug("data", data);
						if(data.result) {
							console.log("form saved successfully");
							console.debug(data);
							var body = "Thank you" + data.name + " for listing your store with Birdie Publishing! \r\nPlease verify all the information you entered as contained in this email: \r\n\r\n" + 
							stripslashes(data.storename) + "\r\n" +
							data.storeaddress1  + "\r\n" +
							data.storeaddress2  + "\r\n" +
							data.storetelephone  + "\r\n" +
							data.email + "\r\n" +
							data.hours  + "\r\n" +
							stripslashes(data.mission)  + "\r\n" +
							data.nonprofit  + "\r\n" +
							data.website + "\r\n" +
							data.taxid + "\r\n" +
							data.taxexempt  + "\r\n" +
							data.resellerpermit  + "\r\n" +
							data.guide + "\r\n" +
							stripslashes(data.charity) + "\r\n\r\n" +
							"If you need to make any changes to your listing please respond to this email immediately.\r\n\r\n Thank you again!\r\nBirdie Publishing";
							
							var emailContent = {'toEmail':data.email, 'subject': 'Thank you for listing with Birdie Publishing!',  
													'body': body, 'from': 'getlisted@birdiepublishing.com' 
												};
							//var mailResult = sendMail(emailContent);
							//console.log("mailresult: ", mailResult);
							var mailResult = true;
							if(mailResult)
							{
								console.log("animating");
								//need to change the screen to the order page here
								var html = stripslashes(data.storename) + "<br>" + data.storeaddress1 + "<br>" + data.storeaddress2 + "<br>" +data.storetelephone + "<br>" + data.website + "<br>" + data.hours + "<br>" + stripslashes(data.mission);
								if(data.charity) 
									html += "<BR>Charity: " + stripslashes(data.charity);
								dojo.byId("templateText").innerHTML = html;
								animateChange("listedForm","listedOrder");
								dojo.byId("custom").value = data.orderid;
							}
						}
						else
						{
							console.log("there was an error saving listing data1");
							var emailContent = {'toEmail':'errors@birdiepublishing.com', 'subject': 'Error in getting listed',  
												'body': data, 'from': 'errors@birdiepublishing.com'
											};
							//sendMail(emailContent);
							
						}
						
					},
					error: function(error) {
						var emailContent = {'toEmail':'errors@birdiepublishing.com', 'subject': 'Error in getting listed',  
												'body': error, 'from': 'errors@birdiepublishing.com'
											};
						//sendMail(emailContent);
						console.log("there was an error saving listing data2");
						
					}
				}
				
				var deferred = dojo.xhrPost(xhrArgs);
			} else
			{
				alert('Form contains invalid data.  Please correct first');
				return false;
			}
		});
	}
	
	/********************************************************/
	/*************Guides catlog******************************/
	/*********************************************************************/
	var productStore = new dojo.data.ItemFileReadStore({url:"getData.php?action=guides"});
	cpGuides = dijit.byId("guides");
	//var mainTab = dijit.byId("mainTab");
	console.log("cpguides loaded");
	//var div =  '<div style=" height:100%; background-color: #fff;-moz-border-radius: 15px; border-radius: 15px; ">';
	//var container = new dijit.layout.BorderContainer({style: "height: 100%; width: 100%;-moz-border-radius: 15px; border-radius: 15px;"});
	var gotList = function(items, request) {
		console.log("in gotList");

		dojo.forEach(items, function(item) {

			var paypalid = productStore.getValue(item, "paypalid");
			var name = productStore.getValue(item, "name");
			var desc = productStore.getValue(item, "description");
			var price = productStore.getValue(item, "unitprice");
			var picture = "images/thumbs/" + productStore.getValue(item, "picture");
			var author = productStore.getValue(item,"author");
			var publishDate = productStore.getValue(item,"publishdate");
			
			price = dojo.currency.format(price, {
				currency: "USD"
			});
			var publishdate = productStore.getValue(item, "publishdate");
			var bc = new dijit.layout.BorderContainer({
				id: paypalid,
				style: "height: 250px; width: 100%;-moz-border-radius: 15px; border-radius: 15px; border: 0px solid; background-color: #99CC66; margin-top:10px;"
			});
			var cpImage = new dijit.layout.ContentPane({
				region: "left",
				style: "margin-left: 2px; margin-bottom:2px; -moz-border-radius-bottomleft: 15px;  -webkit-border-bottom-left-radius:15px;",
				content: '<img src="' + picture + '" alt="' + name + '" height="70px" width="60px" style="padding-top:10px;"/>'
			});
			var cpTitle = new dijit.layout.ContentPane({
				region: "top",
				style: "margin: 2.5px; margin-bottom:0px; -moz-border-radius-topleft: 15px;  -webkit-border-top-left-radius:15px; -moz-border-radius-topright: 15px;  -webkit-border-top-right-radius:15px;",
				content: name + "  -  " + author 
			});
			var cpDesc = new dijit.layout.ContentPane({
				region: "center",
				style: "margin-bottom: 2.5px; font-size:small;",
				content:desc + "<br>Published on " + publishDate
			});
			var cpPay = new dijit.layout.ContentPane({
				region: "right",
				style: "margin-right: 2.5px; margin-bottom:2.5px; -moz-border-radius-bottomright: 15px;  -webkit-border-bottom-right-radius:15px;",
				content:  price
			});
			var div = '<div id="payForm" style="padding-top:130px;"> <form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">' +
				'<input type="hidden" name="cmd" value="_s-xclick">' +
				'<input type="hidden" name="hosted_button_id" value="' + paypalid + '">' +
				'<input type="image" src="https://www.paypal.com/en_US/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal!" >' +
				'<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">' +
				'</form></div>';
			dojo.place(div,cpPay.containerNode,'last');
			bc.addChild(cpImage);
			bc.addChild(cpTitle);
			bc.addChild(cpDesc);
			bc.addChild(cpPay);

			bc.placeAt(cpGuides.containerNode,'last');
			bc.startup();
			bc.resize();
		});

	}
	var gotError = function(error, request) {
		alert("The request to the store failed. " + error);
	}

	productStore.fetch({
		onComplete: gotList,
		onError: gotError
	});
	
	/*********************************************************************/
	/*********************************************************************/
	jump = function(tab) {
		//this function will be used to jump to a specific tab
		var tabs = dijit.byId("mainTab");
		var pane = dijit.byId("publishing");
		tabs.selectChild(pane);
	}
	
	back = function(currentDiv, newDiv) 
	{
		animateChange(currentDiv, newDiv);
	}
	
	

});
