/*
 * extends jquery browser object to trap msie6
 */
jQuery.browser.msie6 = jQuery.browser.msie && parseInt(jQuery.browser.version) == 6 && !window["XMLHttpRequest"];
jQuery.browser.msie7 = jQuery.browser.msie && parseInt(jQuery.browser.version) <= 7 && !window["XMLHttpRequest"];
jQuery.browser.msie8 = jQuery.browser.msie && parseInt(jQuery.browser.version) >= 8 && !window["XMLHttpRequest"];


/*
 * misc config values
 */
config = {
	downOpacity: "0.6",
	initTabWidth: "145px",
	initLabelSrc: "label-main.png",
	destTabWidth: "230px",
	formHeight: "530px"
};

titles = {
	"defaultTitle" : "Académie Culinaire | ",
	"label-main": "Savoir-faire en cuisine",
	"content-01": "Cours de cuisine",
	"content-02": "Activités sur mesure",
	"content-03": "Centre de recherche",
	"content-04": "Un cadeau pour la vie",
	"formulaire" : "Formulaire"
};

var showContentFlag = false;
var slugCurrent = "";

/*
 * Track page in Google Analytics
 */
function trackIt(key1, key2) {

	key = key1;
	if (key1 == undefined) { key = key2.substring(0, key2.indexOf(".")); }
	
	if (key == "") { slug = "" } else { slug = titles[key]; }
	
	if (slug == undefined || slug == slugCurrent) { return false; }
	
	slug = convertAccents(slug.replaceAll(" ", "-").toLowerCase());
	slugCurrent = slug;
	//if (env == "preprod") alert(slug);
	if (env == "prod") pageTracker._trackPageview(slug);
	
}

/*
 * jquery.history.js History change callback
 */
function callback(hash)
{
	// home page, or back to home page
	if (hash == "") {
		// if content is shown, put it back hidden
		if ($("#content").css("height") != undefined) {
			if (uri == "") trackIt("");
			if (!is_static) hideContent();
		}
		$("#main ul").show();
		
    }
	/* show slide content */
	if (hash.indexOf("content") == 0) {
		
		if ($("#content").css("height") != undefined) {
			
			//alert($("#"+hash).attr("href") + ' '+ $("#"+hash).attr("id"));
			nextContent($("#"+hash).attr("href"), $("#"+hash).attr("id"));
		} else {
			showContent($("#"+hash).attr("href"), $("#"+hash).attr("id"));
		}
	}
	// buyflow page
	/*if (hash == "acheter") {
		showContent("formulaire.php", undefined, config.formHeight);
    }*/
}

/*
 * Hook called when initial page loads
 */
function initAnimations() {
	$("#header").fadeIn("slow");
	$("h2").fadeIn("slow");
	$("#bt-programmes").animate({ marginTop: "-10px" }, { queue: false, duration: 200, easing:"easeInOutQuad" });
}

/*
 * Hook called when content page loads
 */
function initContent(id) {
	
	if (!is_ajax) {
	
		$(document).ready(function() {
			// no ajax request, display label text
			changeLabel("content-"+id+"-title.png");
		});
		return false;
	}
	
	// id parameter used for static content-0X.php, not mandatory
	
	if (!$.browser.msie) {
		$('#content .bt, #content .label, #content .cadeau').hide();
		setTimeout("$('#content .bt, #content .label, #content .cadeau').fadeIn()", 500);
	}
	
	$("#bt-acheter").click(function() {
		nextContent($(this).attr("href"), undefined, config.formHeight);
		$.history.load(this.href.replace(/^.*#/, ''));
	    return false;
	});

	$("#bt-retour").click(function() {
		$.history.load(this.href.replace(/^.*#/, ''));
	    return false;
	});
}

/*
 * Hook called when form page loads
 */
function initForm() {
	$('#content form').hide();
	setTimeout("$('#content form').fadeIn()", 200);
}

/*
 * show new page content
 */
function showContent(href, id, destHeight) {

	if (id == undefined) {
		changeLabel();
	} else {
		changeLabel(id+"-title.png");
	}
	/* strip #anchor part of href to load */
	if (href.indexOf("#") != -1) {
		href = href.substring(0, href.indexOf("#"));
	}

	/* split query string from href */
	//data = "";
	var data = parseUriSegments(href);
	//window['acc_data'] = href;
	
	$("#content")
		.load(href, data, function(){
			if (showContentFlag == true) { return false; }
			showContentFlag = true;
			trackIt(id, href);
			$(this)
				.stop()
				.css("height", "358px");

			if ($.browser.msie) {
				
				$(this).show().css("height", (destHeight !== undefined ? destHeight : "358px"));
				
				$("#main ul").hide();
				showContentFlag = false;
			} else {
				
				$(this).animate({ height: (destHeight !== undefined ? destHeight : "358px") }, { duration: 300, easing:"easeOutQuad", complete: function() {
					$("#main ul").hide();
					showContentFlag = false;
				} });
			}
		});
	
}

/*
 * switch from one page content to another
 */
function nextContent(href, id, destHeight) {
	if (!$.browser.msie) {
		$("#content").stop().animate({ height: "0px" }, { duration: 200, easing:"easeOutQuad", complete: function(){
			setTimeout("showContent('"+href+"', undefined, '"+destHeight+"');", 300);
		} });
	} else {
		$("#content").css("height", "0px");
		setTimeout("showContent('"+href+"', undefined, '"+destHeight+"');", 100);
	}
}

/*
 * completely hide content panel
 */
function hideContent() {
	config.itemActive = false;
	changeLabel();
	$("#main ul").show();
	$("#main ul li a span").show();
	
	if (!$.browser.msie) {
		$("#content").stop().animate({ height: "0px" }, { duration: 200, easing:"easeOutQuad", complete: function(){$(this).hide()} });
	} else {
		$("#content").hide();
	}
}

/*
 * change bottom labels
 */
function changeLabel(src) {
	if (src == undefined) { src = config.initLabelSrc; }
	winTitle = src.indexOf("content") == 0 ? titles[src.substring(0,10)] : titles["label-main"];
	if (!config.itemActive) {
		$("h2")
			.css("backgroundImage", "url(images/"+src+")")
			.html(winTitle);
		document.title = titles.defaultTitle + winTitle;
	}
}

/*
 * initialize behaviors, config and animations
 */
$(document).ready(function() {

	overrideJqueryXhr();
	
	$.history.init(callback);
/*
	$("a[rel='history']").click(function(){
    	$.history.load(this.href.replace(/^.*#/, ''));
    	return false;
	});
*/  
	/* show masking div which appears behind last of 4 forfait panels */
	if (!$.browser.msie) {
		$("#main ul").before('<div id="item-mask"></div>');
		var mask = $("#item-mask");
	}
	
	/* hides soon-to-be animated elements */
	$("#header").hide();
	$("h2").hide();
	//$("#content").hide();
	$("#bt-programmes").css("margin-top", "35px");
	
	if (mask != undefined) mask.hide();
	
	/* defines 4-main forfait rollover functions */	
	$("#main ul li a").hover(function() {
				
			
			if (!$(this).hasClass("open")) {
				
				$("#main ul li a.open")
					.stop()
					.removeClass("open")
					.animate({
						width: config.initTabWidth
					}, {
						queue: false,
						duration: 200,
						easing:"easeInOutQuad",
						complete: function(){
							$(this)
								.children("span")
								.fadeIn("fast");
						}
					});
				
				$("#main ul li a")
					.animate({ opacity: "0.6"}, {queue: false});
				
				$(this)
					.stop()
					.animate({
						width: config.destTabWidth
					}, {
						queue: false,
						duration: 350,
						easing:"easeInOutQuad"
					})
					.animate({opacity: "1"}, {queue: false})
					.addClass("open");
				$(this).children("span").fadeOut("fast");
				if (mask != undefined) {
					if ($(this).attr("id") != "content-04") {
						mask.fadeIn("fast");
					} else {
						mask.fadeOut("fast");
					}
				}
				changeLabel($(this).attr("id")+"-title.png");
			}	
		}, function() {
			$(this)
				.stop()
				.animate({
					width: config.initTabWidth
				}, {
					  queue: false,
					  duration: 200,
					  easing:"easeInOutQuad",
						complete: function(){
							$(this).children("span").fadeIn("fast");
							// if no more block do have class="open", put them back full opacity
							if ($("#main ul li a.open").size() == 0) {
								$("#main ul li a").animate({ opacity: "1"});
								if (mask != undefined) mask.fadeOut("fast");
							}
						}
				})
			  	.removeClass("open");
			changeLabel();
		});
	 //}
	
	if (!is_static) { $("#main").prepend($('<div></div>').attr({ id : "content" })); }
	
	/* defines 4-main forfait onclick functions */	
/*
	$("#main ul li a").click(function() {
		if (mask != undefined) mask.fadeOut("fast");
		config.itemActive = $(this).attr("id");
		showContent($(this).attr("href"), $(this).attr("id"));
	    return false;
	});
*/
	
	/* Bottom Programme button slick rollover animation */
	$("#bt-programmes").hover(function() {
		$(this).animate({ marginTop: "-=5px" }, { duration: 100, easing:"easeInOutQuad" });
	}, function() {
		$(this).animate({ marginTop: "+=5px" }, { duration: 50, easing:"easeInOutQuad" });
	});
	
	/* call hook */
	setTimeout("initAnimations()", 500);
});


function overrideJqueryXhr()
{
    $.ajaxSetup({
        xhr: function() {
                if (window.XMLHttpRequest) {
                        return new XMLHttpRequest();
                } else {
                        var progIDs = ['Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'];

                        for (var i = 0; i < progIDs.length; i++) {
                                try {
                                        var xmlHttp = new ActiveXObject(progIDs[i]);
                                        return xmlHttp;
                                } catch (ex) {
                                }
                        }
                        return null;
                }
        }
    });
}


/*
 * check if variable is integer
 */
function isInteger(val) {
	return (val == null || isNaN(val)) ? false : ( ((1.0 * val) == Math.floor(val)) && (val.indexOf(".") == -1));
}

/*
 * parse query string and return object
 */
function parseUriSegments(str) {
	
	if (str.indexOf("?") == -1) return "";
	
	str = str.substring(str.indexOf("?")+1, str.length);
	temp = str.split("&");
	var o = new Object();
	for (i=0; i<temp.length; i++) {
		pair = temp[i].split("=");
		o[pair[0]] = pair[1];
	}
	return o;
}

/*
 * replace accented characters
 */
function convertAccents(str) {

	// ultra ugly lines... don't look at it too long :)
	return str.replaceAll("é", "e")
		.replaceAll("à", "a")
		.replaceAll("â", "a")
		.replaceAll("û", "u")
		.replaceAll("è", "e")
		.replaceAll("ê", "e")
		.replaceAll("ë", "e")
		.replaceAll("ç", "c")
		.replaceAll("î", "i")
		.replaceAll("ô", "o")
		.replaceAll("É", "E")
		.replaceAll("À", "A")
		.replaceAll("Â", "A")
		.replaceAll("Û", "U")
		.replaceAll("È", "E")
		.replaceAll("Ê", "E")
		.replaceAll("Ë", "E")
		.replaceAll("Ç", "C")
		.replaceAll("Î", "I")
		.replaceAll("Ô", "O")
		.replaceAll("'", " ")
		.replaceAll('"', " ")
		.replaceAll("’", " ")

}

/*
 * replace accented characters
 */
function toUpper(str) {
	return str.toUpperCase();
}

/*
 * Replaces all instances of the given substring. Extends string object
 */
String.prototype.replaceAll = function( 
	strTarget, // The substring you want to replace
	strSubString // The string you want to replace in.
	){
	var strText = this;
	var intIndexOfMatch = strText.indexOf( strTarget );
	 
	// Keep looping while an instance of the target string
	// still exists in the string.
	while (intIndexOfMatch != -1){
		// Relace out the current instance.
		strText = strText.replace( strTarget, strSubString )
		 
		// Get the index of any next matching substring.
		intIndexOfMatch = strText.indexOf( strTarget );
	}
	 
	// Return the updated string with ALL the target strings
	// replaced out with the new substring.
	return( strText );
}


