$(document).ready(init);

// Globals
defaultLocation = "Saint-Jérôme, QC, CA";
currentLocation = "";
merchantsArray = new Array();
currentMerchantId = 0;
currentCampaignId = 0;
currentRebateId = 0;
map = null;
cluster = null;

// Initializing the map
google.load("maps", "2", {
			"language" : clientCulture
		});
google.setOnLoadCallback(gMapReady);

function init() {
	// Initializing the jQuery tab panel
	$('#tabs').tabs();
	$('#tabs').tabs('select', 1);
	$('#tabs').bind('tabsshow', function(event, ui) {
				if (ui.panel.id == "fragment-1") {
					resizeMap();
				}
			});
	// Hover states on the static widgets
	$('#dialog_link, ul#icons li').hover(function() {
				$(this).addClass('ui-state-hover');
			}, function() {
				$(this).removeClass('ui-state-hover');
			});
	// Attaching events to the DOM
	$('#location-field').bind('focus', clearField);
	$('#subscribenewsletter').bind('click', subscribeNewsletter);
	$('#contactus').bind('click', contactUs);
	$('#allrebatesbutton').bind('click', showCarousel);
	$('#send_merchant').bind('click', sendToMerchant);
	// Initialize dialogs
	var buttons = new Object();
	buttons[dictionary['Change Location']] = function() {
		var loc = $('#loc').fieldValue()[0];
		if (!loc) {
			loc = getAutoClientLocation();
		}
		updateLocationInfo(loc);
		$(this).dialog('close');
	};
	buttons[dictionary['Cancel']] = function() {
		$(this).dialog('close');
	};
	$("#confirmloc").dialog({
				autoOpen : false,
				bgiframe : true,
				buttons : buttons,
				close : function() {
				}
			});
	buttons = new Object();
	buttons[dictionary['Send']] = function() {
		var friendname = $('#friendname').fieldValue()[0];
		var friendemail = $('#friendemail').fieldValue()[0];
		var yourname = $('#yourname').fieldValue()[0];
		var youremail = $('#youremail').fieldValue()[0];
		var sendToAfriendMessage = $('#sendtoafriendmessage').fieldValue()[0];
		if (friendname && friendemail && yourname && youremail) {
			sendToAFriend(friendname, friendemail, yourname, youremail,
					sendToAfriendMessage);
		} else {
			$(this).dialog('close');
		}
		$(this).dialog('close');
	};
	buttons[dictionary['Cancel']] = function() {
		$(this).dialog('close');
	};
	$("#confirmsendtoafriend").dialog({
				autoOpen : false,
				bgiframe : true,
				buttons : buttons,
				close : function() {
				}
			});
	buttons = new Object();
	buttons[dictionary['Send']] = function() {
		var yournamecontactus = $('#yournamecontactus').fieldValue()[0]
		var youremailcontactus = $('#youremailcontactus').fieldValue()[0];
		var messagecontactus = $('#messagecontactus').fieldValue()[0];
		if (yournamecontactus && youremailcontactus && messagecontactus) {
			sendContactUs(yournamecontactus, youremailcontactus,
					messagecontactus);
		} else {
			$(this).dialog('close');
		}
		$(this).dialog('close');
	};
	buttons[dictionary['Cancel']] = function() {
		$(this).dialog('close');
	};
	$("#confirmcontactus").dialog({
				autoOpen : false,
				bgiframe : true,
				buttons : buttons,
				close : function() {
				}
			});
	$("#alertsendtoafriendok").dialog({
				autoOpen : false,
				bgiframe : true,
				buttons : {
					'Ok' : function() {
						$(this).dialog('close');
					}
				},
				close : function() {
				}
			});
	$("#alertsendtoafrienderror").dialog({
				autoOpen : false,
				bgiframe : true,
				buttons : {
					'Ok' : function() {
						$(this).dialog('close');
					}
				},
				close : function() {
				}
			});
	$('#alertsubscribenewsletterok').dialog({
				autoOpen : false,
				bgiframe : true,
				buttons : {
					'Ok' : function() {
						$(this).dialog('close');
					}
				},
				close : function() {
				}
			});
	$('#alertsubscribenewsletterbademailerror').dialog({
				autoOpen : false,
				bgiframe : true,
				buttons : {
					'Ok' : function() {
						$(this).dialog('close');
					}
				},
				close : function() {
				}
			});
	$('#alertsubscribenewsletteralreadysubscribederror').dialog({
				autoOpen : false,
				bgiframe : true,
				buttons : {
					'Ok' : function() {
						$(this).dialog('close');
					}
				},
				close : function() {
				}
			});
	$('#alertsubscribenewsletterbadlocationerror').dialog({
				autoOpen : false,
				bgiframe : true,
				buttons : {
					'Ok' : function() {
						$(this).dialog('close');
					}
				},
				close : function() {
				}
			});
	$('#alertsubscribenewslettermissingfieldserror').dialog({
				autoOpen : false,
				bgiframe : true,
				buttons : {
					'Ok' : function() {
						$(this).dialog('close');
					}
				},
				close : function() {
				}
			});
	$('#alertsubscribenewsletterunexpectederror').dialog({
				autoOpen : false,
				bgiframe : true,
				buttons : {
					'Ok' : function() {
						$(this).dialog('close');
					}
				},
				close : function() {
				}
			});
	$('#alertcontactusok').dialog({
				autoOpen : false,
				bgiframe : true,
				buttons : {
					'Ok' : function() {
						$(this).dialog('close');
					}
				},
				close : function() {
				}
			});
	$('#alertcontactuserror').dialog({
				autoOpen : false,
				bgiframe : true,
				buttons : {
					'Ok' : function() {
						$(this).dialog('close');
					}
				},
				close : function() {
				}
			});
	$('#alertsendtoamerchantok').dialog({
				autoOpen : false,
				bgiframe : true,
				buttons : {
					'Ok' : function() {
						$(this).dialog('close');
					}
				},
				close : function() {
				}
			});
	$('#alertsendtoamerchantmissingfieldserror').dialog({
				autoOpen : false,
				bgiframe : true,
				buttons : {
					'Ok' : function() {
						$(this).dialog('close');
					}
				},
				close : function() {
				}
			});
	$('#alertsendtoamerchantwrongcaptchaerror').dialog({
				autoOpen : false,
				bgiframe : true,
				buttons : {
					'Ok' : function() {
						$(this).dialog('close');
					}
				},
				close : function() {
				}
			});
	$('#alertsendtoamerchanterror').dialog({
				autoOpen : false,
				bgiframe : true,
				buttons : {
					'Ok' : function() {
						$(this).dialog('close');
					}
				},
				close : function() {
				}
			});
	showCarousel();

}

// Location functions
function gMapReady() {
	var location = '';
	// Getting the location cookie
	var loc = getCookie('loc');
	if (loc != null) {
		location = loc;
	} else {
		// No location cookie, let's get a google maps fix
		location = getAutoClientLocation();
	}
	updateLocationInfo(location);
}

function getAutoClientLocation() {
	var location = "";
	if (google.loader.ClientLocation) {
		var city = google.loader.ClientLocation.address.city;
		var region = google.loader.ClientLocation.address.region;
		var country = google.loader.ClientLocation.address.country_code;
		if (city) {
			location += city;
			if (region) {
				location += ", " + region;
			}
			if (country) {
				location += ", " + country;
			}
		}
	} else {
		location = defaultLocation;
	}
	return location;
}
// Map functions
function getMap() {
	var location = '';
	var latitude = 0;
	var longitude = 0;
	location = currentLocation;
	var markers = new Array();
	var geocoder = new GClientGeocoder();
	map = new GMap2(document.getElementById("map"));
	map.disableDoubleClickZoom();
	var merchantPoint = new GLatLng(merchantLat, merchantLong);
	geocoder.getLatLng(location, function(point) {
				if (!point) {
					displayDialog($("#confirmloc"));
				} else {
					var clientMarker = new GMarker(point);
					var merchantMarker = createMarker(merchantPoint,
							'/images/marker_def.png', 70.0, 90.0);
					GEvent.addListener(clientMarker, "click", function() {
								var myHtml = dictionary['Your Location']
										+ ': <br/><strong>' + location
										+ '</strong>';
								clientMarker.openInfoWindowHtml(myHtml);
							});
					GEvent.addListener(merchantMarker, "click", function() {
								var myHtml = '<strong>' + merchantName
										+ '</strong>';
								merchantMarker.openInfoWindowHtml(myHtml);
							});
					markers.push(clientMarker);
					markers.push(merchantMarker);
					cluster = new ClusterMarker(map, {
								markers : markers
							});
					cluster.fitMapToMarkers();
				}
			});
}

function createMarker(point, url, width, height) {
	var icon = createIcon(url, width, height);
	var marker = new GMarker(point, icon);
	return marker;
}

function createIcon(url, width, height) {
	var icon = new GIcon();
	icon.image = url;
	icon.shadow = "/images/marker_shadow_ciseaux.png";
	icon.iconSize = new GSize(width, height);
	icon.shadowSize = new GSize(74.0, 90.0);
	icon.iconAnchor = new GPoint(18, 89);
	icon.infoWindowAnchor = new GPoint(32, 24);
	return icon;
}
// AJAX functions
function sendToAFriend(friendname, friendemail, yourname, youremail,
		sendtoafriendmessage) {
	var host = getHost();
	$.post("http://" + host + "/" + clientCulture + "/index/sendToAFriend",
			{
				friendname : friendname,
				friendemail : friendemail,
				yourname : yourname,
				youremail : youremail,
				merchantid : currentMerchantId,
				campaignid : currentCampaignId,
				rebateid : currentRebateId,
				sendtoafriendmessage : sendtoafriendmessage
			}, function(data) {
				if (data == 'ok') {
					displayDialog($('#alertsendtoafriendok'));
				} else {
					displayDialog($('#alertsendtoafrienderror'));
				}
			});

}
function subscribeNewsletter() {
	var host = getHost();
	$.post(	"http://" + host + "/" + clientCulture
					+ "/index/subscribeNewsletter", {
				yourname : $('#yournamenewsletter').fieldValue()[0],
				youremail : $('#youremailnewsletter').fieldValue()[0],
				yourlocation : $('#yourlocation').fieldValue()[0],
				radius : $('#radius').fieldValue()[0],
				ebonismartnewsletter : $('#ebonismartnewsletter').fieldValue()[0],
				merchantid : merchantId
			}, function(data) {
				switch (data) {
					case "ok" :
						displayDialog($('#alertsubscribenewsletterok'));
						break;
					case "bademail" :
						displayDialog($('#alertsubscribenewsletterbademailerror'));
						break;
					case "alreadysubscribed" :
						displayDialog($('#alertsubscribenewsletteralreadysubscribederror'));
						break;
					case "badlocation" :
						displayDialog($('#alertsubscribenewsletterbadlocationerror'));
						break;
					case "missingfields" :
						displayDialog($('#alertsubscribenewslettermissingfieldserror'));
						break;
					default :
						displayDialog($('#alertsubscribenewsletterunexpectederror'));
				}
			});
	return false;
}

function sendToMerchant() {
	var host = getHost();
	var name = $('#namesendtoamerchant').fieldValue()[0];
	var email = $('#emailsendtoamerchant').fieldValue()[0];
	var phone = $('#phonesendtoamerchant').fieldValue()[0];
	var question = $('#questionsendtoamerchant').fieldValue()[0];
	var merchantid = $('#merchantidsendtoamerchant').fieldValue()[0];
	var rid = $('#ridsendtoamerchant').fieldValue()[0];
	var cid = $('#cidsendtoamerchant').fieldValue()[0];
	var token = $('#tokensendtoamerchant').fieldValue()[0];
	var captcha = $('#captchasendtoamerchant').fieldValue()[0];
	$.post(	"http://" + host + "/" + clientCulture
					+ "/merchant/sendToMerchant", {
				name : name,
				email : email,
				phone : phone,
				question : question,
				merchantid : merchantId,
				rid : rid,
				cid : cid,
				token : token,
				captcha : captcha
			}, function(data) {
				try {
					var responseObject = $.secureEvalJSON(data);
				} catch (e) {
					displayDialog($('#alertsendtoamerchanterror'));
					$('#tokensendtoamerchant').val('dummy');
					var captchaImageSrc = $('#captchaimagesendtoamerchant').attr('src');
					captchaImageSrc = captchaImageSrc.split('?')[0];
					var date = new Date();
					captchaImageSrc = captchaImageSrc + '?t=' + date.valueOf();
					$('#captchaimagesendtoamerchant').attr('src', captchaImageSrc);
				}
				$('#tokensendtoamerchant').val(responseObject.token);
				var captchaImageSrc = $('#captchaimagesendtoamerchant').attr('src');
				captchaImageSrc = captchaImageSrc.split('?')[0];
				var date = new Date();
				captchaImageSrc = captchaImageSrc + '?t=' + date.valueOf();
				$('#captchaimagesendtoamerchant').attr('src', captchaImageSrc);
				switch (responseObject.message) {
					case "ok" :
						displayDialog($('#alertsendtoamerchantok'));
						break;
					case "wrongcaptcha" :
						displayDialog($('#alertsendtoamerchantwrongcaptchaerror'));
						break;
					case "missingfields" :
						displayDialog($('#alertsendtoamerchantmissingfieldserror'));
						break;
					default :
						displayDialog($('#alertsendtoamerchanterror'));
				}
			});
	return false;
}

function sendContactUs(yourname, youremail, yourmessage) {
	var host = getHost();
	$.post("http://" + host + "/" + clientCulture + "/index/contactUs", {
				yourname : yourname,
				youremail : youremail,
				yourmessage : yourmessage
			}, function(data) {
				if (data == 'ok') {
					displayDialog($('#alertcontactusok'));
				} else {
					displayDialog($('#alertcontactuserror'));
				}
			});
}
// UI functions
function openSendToAFriend(rebateString) {
	var rebateData = rebateString.split('/');
	currentMerchantId = rebateData[0];
	currentCampaignId = rebateData[1];
	currentRebateId = rebateData[2];
	displayDialog($('#confirmsendtoafriend'));
}
function displayDialog(el) {
	el.dialog("open");
}
function resizeMap() {
	map.checkResize();
	cluster.fitMapToMarkers();
}
function updateLocationInfo(loc) {
	$('#yourlocation').val(loc);
	currentLocation = loc;
	setCookie('loc', loc, 365, '/');
	getMap();
}
function contactUs() {
	displayDialog($('#confirmcontactus'));
	return false;
}
function showRebateValue(totalRebateValue) {
	if (parseInt(totalRebateValue) == parseFloat(totalRebateValue)) {
		totalRebateValue += '.00'
	}
	$('#rebatetotalvalue').text(totalRebateValue + '$');
}
function showLoader() {
	// $('#loader').css({top:'400px',left:'400px'});
	// $('#loader').show();
}
// For the buttons, jQuery UI CSS framework function
$(function() {
	// all hover and click logic for buttons
	$(".button:not(.ui-state-disabled)").hover(function() {
				$(this).addClass("ui-state-hover");
			}, function() {
				$(this).removeClass("ui-state-hover");
			}).mousedown(function() {
		$(this).parents('.fg-buttonset-single:first')
				.find(".fg-button.ui-state-active")
				.removeClass("ui-state-active");
		if ($(this)
				.is('.ui-state-active.fg-button-toggleable, .fg-buttonset-multi .ui-state-active')) {
			$(this).removeClass("ui-state-active");
		} else {
			$(this).addClass("ui-state-active");
		}
	}).mouseup(function() {
		if (!$(this)
				.is('.fg-button-toggleable, .fg-buttonset-single .fg-button,  .fg-buttonset-multi .fg-button')) {
			$(this).removeClass("ui-state-active");
		}
	});
});

// Agile Carrousel functions
function showCarousel() {
	if (allRebatesButton) {
		$('#allrebatesbuttoncontainer').show();
		$('#inner_button').show();
		$('#slide_holder').html($('#rebatehtml').html());
		allRebatesButton = false;
	} else {
		if (!singleRebateBar) {
			$('#allrebatesbuttoncontainer').hide();
		} else {
			$('#allrebatesbuttoncontainer').show();
			$('#slide_holder').html($('#rebatehtml').html());
			return;
		}
		$('#inner_button').hide();
		var host = getHost();
		$('#slide_holder').agile_carousel({
			first_last_buttons : "no",
			hover_next_prev_buttons : "no",
			next_prev_buttons : "yes",
			pause_button : "no",
			slide_buttons : "yes",
			// slide_captions: "JQuery Carousel Plugin|Agile Slide
			// Types|JQuery UI Effects Available|Agile Settings|Carousel
			// That's Built to Order",
			slide_directory : "rebates/" + clientCulture + "/htmlmerchant/"
					+ merchantUrlStump,
			// slide_links:
			// "http://code.google.com/p/agile-carousel/downloads/list,http://code.google.com/p/agile-carousel/downloads/list,http://code.google.com/p/agile-carousel/downloads/list,http://code.google.com/p/agile-carousel/downloads/list,http://code.google.com/p/agile-carousel/downloads/list",
			slide_number_display : "no",
			timer_on : "no",
			// timer_length : "7000",
			transition_duration : 1000,
			transition_easing : "easeInOutSine",
			transition_type : "carousel",
			water_mark : "no"
		});

	}
}

// Utility functions
function clearField(e) {
	var field = $(e.target);
	field.val('');
}
function replaceContent(el, html) {
	el.empty();
	el.append(html);
}
function truncateText(text, len) {
	var truncatedText = "";
	var trunc = text;
	if (text.length > len) {
		/*
		 * Truncate the content of the P, then go back to the end of the
		 * previous word to ensure that we don't truncate in the middle of a
		 * word
		 */
		trunc = trunc.substring(0, len);
		trunc = trunc.replace(/\w+$/, '');

		/*
		 * Add an ellipses to the end
		 */
		trunc += '(...)';
		truncatedText = trunc;
	}
	return truncatedText;
}
function stripHTML(html) {
	var matchTag = /<(?:.|\s)*?>/g;
	return html.replace(matchTag, "");
}
function getHost() {
	var host = window.location.host;
	if (host == "localhost")
		host += "/frontend_dev.php";
	return host;
}