$(document).ready(init);

// Globals
defaultLocation = "Saint-Jérôme, QC, CA";
currentLocation = "";
merchantsArray = new Array();
currentMerchantId = 0;
currentCampaignId = 0;
currentRebateId = 0;

// Initializing the map
google.load("maps", "2", {
			"language" : clientCulture
		});
google.setOnLoadCallback(gMapReady);

function init() {
	// Initializing the jQuery tab panel
	$('#tabs').tabs();
	// 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
	$('#change_loc').bind('click', changeLocation);
	$('#location-field').bind('focus', clearField);
	$('#subscribenewsletter').bind('click', subscribeNewsletter);
	$('#contactus').bind('click', contactUs);
	// 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() {
				}
			});
	// Retrieve marker locations
	retrieveMarkerLocations();

}

// Location functions
function changeLocation(e) {
	var location = "";
	location = $('#location-field').fieldValue()[0];
	if (!location) {
		displayDialog($("#confirmloc"));
	} else {

	}
	updateLocationInfo(location);
}

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 updateMap() {
	var location = '';
	var latitude = 0;
	var longitude = 0;
	var totalRebateValue = 0;
	var markers = new Array();
	location = currentLocation;
	var map = new google.maps.Map2(document.getElementById("map"));
	map.disableDoubleClickZoom();
	var bottomLeft = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(10,
					10));
	var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,
					10));

	map.addControl(new GSmallMapControl(), bottomLeft);
	map.addControl(new GMapTypeControl(), bottomRight);

	var geocoder = new GClientGeocoder();
	var merchantArraySize = merchantsArray.length;
	for (var i = 0; i < merchantArraySize; i++) {
		latitude = merchantsArray[i]['lat'];
		longitude = merchantsArray[i]['long'];
		var latlng = new GLatLng(latitude, longitude);
		var urlStump = merchantsArray[i]['urlstump'];
		var merchantDescription = merchantsArray[i]['description'];
		var merchantName = merchantsArray[i]['name'];
		var merchantMarker = createMarker(latlng, '/images/'
						+ merchantsArray[i]['iconname'], 70.0, 90.0, urlStump,
				merchantName, merchantDescription);
		var rebates = merchantsArray[i]['rebates'];
		var numRebates = rebates.length;
		for (var j = 0; j < numRebates; j++) {
			var rebateValue = rebates[j]['value'];
			if (rebateValue.indexOf('$') != -1) {
				rebateValue = rebateValue.split('$')[0];
				totalRebateValue += rebateValue * 1;
			} else {

			}
		}
		markers.push(merchantMarker);
	}
	showRebateValue(totalRebateValue);
	geocoder.getLatLng(location, function(point) {
				if (!point) {
					displayDialog($("#confirmloc"));
				} else {
					// map.setCenter(point, 9);
					var clientMarker = new GMarker(point);
					GEvent.addListener(clientMarker, "click", function() {
								var myHtml = dictionary['Your Location']
										+ ': <br/><strong>' + location
										+ '</strong>';
								clientMarker.openInfoWindowHtml(myHtml);
							});

					markers.push(clientMarker);
					var cluster = new ClusterMarker(map, {
								markers : markers
							});
					cluster.clusterMarkerIcon = createIcon(
							 "/images/marker_plus_"+clientCulture+".png", 70.0, 90.0);
					cluster.clusterMarkerTitle = '%count '
							+ dictionary['Bonismart rebates: click me!'];
					cluster.fitMapToMarkers();
					clientMarker.openInfoWindowHtml(dictionary['Your Location']
							+ ': <br/><strong>' + location + '</strong>');
				}
			});

}

function createMarker(point, url, width, height, urlStump, merchantName,
		merchantDescription) {
	var icon = createIcon(url, width, height);
	var marker = new GMarker(point, icon);
	GEvent.addListener(marker, "click", function() {
				showLoader();
				showCarousel(urlStump, merchantName, merchantDescription);
			});
	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(0, 53);
	return icon;
}
// AJAX functions
function retrieveMarkerLocations() {
	var host = getHost();
	$.post(	"http://" + host + "/" + clientCulture
					+ "/index/retrieveMerchantInfo", function(data) {
				merchantsArray = $.secureEvalJSON(data);
				updateMap();
			});

}
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 : ''
			}, 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 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 updateLocationInfo(loc) {
	replaceContent($('#location'), loc);
	$('#yourlocation').val(loc);
	currentLocation = loc;
	updateMap();
	setCookie('loc', loc, 365, '/');
}
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(urlStump, merchantName, merchantDescription) {
	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_directory : "rebates/" + clientCulture + "/htmlindex/" + urlStump,
		slide_number_display : "no",
		timer_on : "no",
		transition_duration : 1000,
		transition_easing : "easeInOutSine",
		transition_type : "carousel",
		water_mark : "no"
	});
	$('#bloc7_7').html('<p>'
			+ truncateText(stripHTML(merchantDescription), 110) + '</p>');
	$('#bloc7_9').html('<a href="http://' + host + '/' + clientCulture
			+ '/merchant/' + urlStump + '">' + merchantName + '</a>');
}

// 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 += "/bonismart_v1/web/frontend_dev.php";
	return host;
}