$(document).ready(function($) {
	$('a[rel^="ext"]').attr('target', '_blank');
	
 //$("#subscribe-email").defaultValue("submit email address");

	selectMainMenu("mm-");
	$("#main-menu-sub li:last").css({'background-image' : 'none'});
	
	//if(currpage == "common-questions"){
		commonQuestions();
	//}
	



});

function openReview(page, lang){
	$.prettyPhoto.open(page+'&iframe=true&width=640&height=480&lang='+lang,'','');	
};

function openAeroplan(page, lang){
	if(lang == "fr")
		$.prettyPhoto.open(page+'&iframe=true&width=658&height=580&lang='+lang,'','');	
	else
		$.prettyPhoto.open(page+'&iframe=true&width=658&height=540&lang='+lang,'','');	
};

function sendForm(f){
		jQuery('#'+f).ajaxSubmit({
		beforeSubmit: presubmitResume,
		success: submitResume,
		error: errorresponse,
		resetForm: false
	});
}

	function presubmitResume(){
	};

	function submitResume(data){
		msgresponse(data,"message-error","","message-success","",hideform);		
	};

	function hidefranchiseform(d){				
		if(d.err == ''){
			$('#franchiseform').hide();
			$('#franchise-confirm').show();			
		}else{
		}		
	}
	
	function hideform(d){				
		if(d.err == ''){
			$('#resumeform').hide();
			$('#resume-confirm').show();			
		}else{
		}		
	}
	
	function hidereview(d){				
		if(d.err == ''){
			$('#reviewform').hide();
			$('#review-confirm').show();			
		}else{
		}		
		$('#rating-container').unblock();
	}

	function msgresponse(data, thediv, erroraction, successdiv, anaction, callback){

		if (typeof anaction == "undefined") {
			anaction = "";
		}

		if (typeof erroraction == "undefined") {
			erroraction = "";
		}

		if (typeof callback != "function") {
			callback = false;
		}

		var displaydiv = null;
		var mess = "";
		var theaction = null;
		try{
			data = JSON.parse(data);

			if(data.err != ''){
				mess = data.err;
				if(typeof(mess) != "string"){
					mess = formatErrs(mess);
				}
				displaydiv = thediv;
				theaction = erroraction;

			}else{
				mess = data.msg;
				displaydiv = successdiv;
				theaction = anaction;
			}
			if(theaction == ""){
				//clearMessages();
				$('#'+displaydiv).show();
				$('#'+displaydiv).html(mess);
			}else if(theaction == "redirect"){
				window.location = mess;
			}else if(theaction == "debug"){
				alert(mess);
			}


			if(callback != false){
				callback(data);
			}


		}catch(err){
			var txt = err + "\n\n";
			txt += data;
			alert(txt);
		}

	};

	function errorresponse(xhr, status, e){
		alert("Error: Could not Submit Form. Please try again.");
	}

function commonQuestions(){
	
			$('.question h2').live('click', function(){
				var el = $(this);
				var q = el.parent();
				var p = q.find('.answer');
				
				if(p.css("display") == "none"){
					p.slideDown();
					q.addClass("on");
				}else{
					p.slideUp();
					q.removeClass("on");
				}
				
			});
	
};

function customRange(input) {
		return {minDate: (input.id == "check_out" ? $("#check_in").datepicker("getDate") : null), maxDate: (input.id == "check_in" ? $("#check_out").datepicker("getDate") : null)};
};

function nl2br(str, is_xhtml) {
	var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
	return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}

function utf8_encode ( argString ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Ulrich
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'

    var string = (argString+''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");

    var utftext = "";
    var start, end;
    var stringl = 0;

    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;

        if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }

    if (end > start) {
        utftext += string.substring(start, string.length);
    }

    return utftext;
}

function base64_encode (data) {
    // http://kevin.vanzonneveld.net
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Bayron Guevara
    // +   improved by: Thunder.m
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // *     example 1: base64_encode('Kevin van Zonneveld');
    // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='

    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof this.window['atob'] == 'function') {
    //    return atob(data);
    //}
        
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = [];

    if (!data) {
        return data;
    }

    data = utf8_encode(data+'');
    
    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);

        bits = o1<<16 | o2<<8 | o3;

        h1 = bits>>18 & 0x3f;
        h2 = bits>>12 & 0x3f;
        h3 = bits>>6 & 0x3f;
        h4 = bits & 0x3f;

        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);
    
    enc = tmp_arr.join('');
    
    switch (data.length % 3) {
        case 1:
            enc = enc.slice(0, -2) + '==';
        break;
        case 2:
            enc = enc.slice(0, -1) + '=';
        break;
    }

    return enc;
}

function spaceHours(str){
	str = str.replace("Sat:","<br/>Sat:");
	return str;
};

function showServices(el){
	var p = $("#"+el);

	if(p.css("display") == "block"){
		p.slideUp();
	}else{
		p.slideDown();		
	}
}

var active_toggle = null;
function toggle(el, thelink){
	thelink = $('#'+thelink);
	
	el = $('#'+el);
	var thetoggle = el;

	if(active_toggle != null){
			thelink.removeClass("over");
			active_toggle.slideUp('normal');
			$('.check-value').attr('checked', false);

			if(active_toggle.attr("id") != thetoggle.attr("id")){
				showToggle(thetoggle);
				thelink.addClass("over");
				
			}else{
				active_toggle = null;
			}
	}else{
		showToggle(thetoggle);
		thelink.addClass("over");
	}

};


function showToggle(thetoggle){
	thetoggle.show(150);
	active_toggle = thetoggle;
};

var prevpage = "";
var prevsubpageactive = "";

function selectMainMenu(prefix, idx){
	if(idx ==undefined){
		idx = 0;
	}
	
	if(pages !== undefined){
		var thepagename = (pages[0] == "") ? "home": pages[0];
		$("#"+prefix+thepagename).addClass("selected");
		if(prevpage !=""){
			$("#"+prefix+prevpage).removeClass("selected");
		}
		//alert("#"+prefix+thepagename);
		prevpage ="#"+prefix+thepagename;
	}

};


function initSelectfade(){
	var l = $("#promotions-list li img");
	var img_container =  $("#promotions-image");
	var mainimg;
	
	l.live('click',function() {
		var el = $(this);
		l.removeClass("selected");
		el.addClass("selected");
		var img_id = el.attr("id").replace("sm-","lg-");
		var new_img = $("#"+img_id);

		mainimg = $("#promotions-image div.selected");
		var new_src = el.attr("src").replace("_sm","_lg");
		var el_alt = el.attr("alt");	
	
	  mainimg.fadeOut('fast', function() { 
		  mainimg.removeClass("selected");
		  img_container.height(new_img.height()+30);
		  //new_img.find('img').show();
		  new_img.fadeIn('slow');
		  new_img.addClass("selected");	
	   });

	 });

	var html = '';
	var initial = '';
	var initial_img = '';
	$.each(l, function (i,v){
		var el = $(this);
		el.attr("id",'sm-img-'+i)
		var new_src = el.attr("src").replace("_sm","_lg");
		var el_alt = el.attr("alt");
		
		if(i == 0){
			el.addClass("selected");
			initial = ' style="display:block"';
			initial_img = ' selected';
		}else{
			initial = '';
			initial_img = '';
		}
		
		var print_text = (lang == "en") ? 'Print Promotion': 'Imprimer';
		html += '<div id="lg-img-'+i+'" class="promotion-item'+initial_img+'"'+initial+'><div class="print-link"><a href="javascript:void(0)" onclick="openBrWindow(this)">'+print_text+'</a></div><div class="hide-promo"><img src="'+new_src+'" alt="'+el_alt+' - Large" /></div></div>';
	});
	img_container.html(html);
	//mainimg = $("#promotions-image .selected");
	img_container.height(mainimg.height()+30);
};

function openBrWindow(el) {
	el = $(el);
	var theimg = el.parent().parent().find('img');	
	features = "toolbar=yes,location=yes,status=yes,menubar=no,scrollbars=no,width="+theimg.width()+",height="+theimg.height();
  window.open(theimg.attr("src"),"promo",features);
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}