// init
$(document).ready(function(){
	changeFontSize();
	tooltipMenuTop();
	callLocator();
	accordeonNews();
	carousel();
	tabs();
	menuLeft();
	tool();
	cookie();
	dropDown();
	launchEdit();
	tooltipReadMe();
	enable_edits();
	launchOnlineService();
	launchLocatorFromNav();
	documentLinksToSoftClick();
	referrer();
});

// check the referre to show a modal window
function referrer() {
    if ((document.referrer) == "http://www.merchantbanking.fortis.com/splash.html" ||  (document.referrer) == "http://www.fortisbusiness.com/splash.html") {
        var msg = "<div id='modal'></div><div id='wrapper_bookmark_msg'><div id='bookmark_msg'><div id='content'><p><span>Dear visitor,</span><br />For your own convenience we suggest you to bookmark this site.<br>Click yes, if you would like to bookmark this site.</p><div class='wrapper_btn'><a href='#' class='btn_splash' id='bookmark'>YES</a><a href='#' class='btn_splash' id='exit'>NO</a></div></div></div></div>"

        $(msg).appendTo('body');
        $("#modal").show();
        $("#exit").bind('click', function() {
            $("#modal, #bookmark_msg").remove();
        });
        if (window.opera) {
            $("#modal, #bookmark_msg").remove();
            if ($("a#bookmark").attr("rel") != "") { // don't overwrite the rel attrib if already set  
                $("a#bookmark").attr("rel", "sidebar");
            }
        }

        $("a#bookmark").click(function(event) {
            $("#modal, #bookmark_msg").remove();
            event.preventDefault(); // prevent the anchor tag from sending the user off to the link  
            var url = this.href;
            var title = document.title;

            if (window.sidebar) { // Mozilla Firefox Bookmark  
                window.sidebar.addPanel(title, url, "");
            } else if (window.external) { // IE Favorite  
                window.external.AddFavorite(url, title);
            } else if (window.opera) { // Opera 7+  
                return false; // do nothing - the rel="sidebar" should do the trick  
            } else { // for Safari, Konq etc - browsers who do not support bookmarking scripts (that i could find anyway)  
                alert('Unfortunately, this browser does not support the requested action,'
	             + ' please bookmark this page manually.');
            }

        });
    }

}


function changeFontSize() {
	// change size of site
	$(".font a.less").click(function(){
		$("body").removeClass("large");
		$("body").addClass("narrow");
		$.cookie('font', 'narrow');
		return false;
	});
	$(".font a.regular").click(function(){
		$("body").removeClass("narrow");
		$("body").removeClass("large");
		$.cookie('font', 'regular');
		return false;
	});
	$(".font a.more").click(function(){
		$("body").removeClass("narrow");
		$("body").addClass("large");
		$.cookie('font', 'large');
		return false;
	});
}

function tooltipMenuTop() {
	// tooltip menu nav
	$("ul.menu_nav li a").hoverIntent(function(){
		$(this).next('em').fadeIn('fast');
	},
		function(){
		$(this).next('em').fadeOut('slow');
		}
	);
}

function callLocator() {
	// call locator
	$(".locator").click(function(){
		var d = new Date();
		$("#modal").show();
		$("#wrapper_modal_content").show();
	 	$("#wrapper_modal_content").load("/01/Modules/Fortis_BusinessLocator_ModuleTemplates/BusinessLocatorRedirection.aspx?redirect=1");
		return false;
	})

		// call locator
	$(".locatorRedirect").click(function(e){
		var d = new Date();
		var selectedLinkHref = window.event ? e.srcElement.href : e.target.href;
		$("#modal").show();
		$("#wrapper_modal_content").show();
		$("#wrapper_modal_content").load("/01/Modules/Fortis_BusinessLocator_ModuleTemplates/BusinessLocatorRedirection.aspx?href=" + selectedLinkHref);
	 	//$("#wrapper_modal_content").load("/01/Modules/Fortis_BusinessLocator_ModuleTemplates/flash/locator.html");
		return false;
	})
	
		// call locator
	$(".OSlocator").click(function(){ 
		var d = new Date();
		$("#modal").show();
		$("#wrapper_modal_content").show();
	 	$("#wrapper_modal_content").load("/01/Modules/Fortis_BusinessLocator_ModuleTemplates/BusinessLocatorRedirection.aspx?redirect=1&onlineservices=true");
		return false;
	})


}

function accordeonNews() {
	// accordeon homepage
	$(".wrapper_news").hoverIntent(
		function(){
			$(".wrapper_news .news").addClass("expand");
			$(".wrapper_news .news p.hidden").addClass("to_show");
			$(".sidebar .to_hide").animate({height:"27px"}, 500);
	},function(){
		$(".wrapper_news .news").removeClass("expand");
		$(".wrapper_news .news p.hidden").removeClass("to_show");
		$(".sidebar .to_hide").animate({height:"93px"}, 500);
	}
	);
}

function carousel() {
	// carrousel service internal
	$(".car").jCarouselLite({
        btnNext: ".next",
        btnPrev: ".prev",
				visible: 1,
				speed: 800
  });
}

function tabs() {
		//tabs
	$('div.tabbed div').hide();
	$('div.t1').show();
	$('div.tabbed ul.tabs li.t1').addClass('selected');

	$('div.tabbed ul.tabs li').click(function(){
		var thisClass = this.className.slice(0,2);
		$('div.tabbed div').hide();
		$('div.' + thisClass).show();
		$('div.tabbed ul.tabs li').removeClass('selected');
		$(this).addClass('selected');
		return false;
	});
}
	
function menuLeft() {
	// put empty icon if menu has not subitem
	$(".sidebar .menu_sidebar ul li").each(function(){
		if ( $(this).find("ul").length == 0 )
		{
			$(this).addClass("empty");	
		}
	});
	// expand menu navigation left
	$(function(){
		$(".menu_sidebar li span").toggle(function() {
			$(this).nextAll('ul').slideToggle('fast');
			$(this).addClass("open");
		},function(){
			$(this).nextAll('ul').slideUp('fast');
			$(this).removeClass("open");
		});
	})
}
	
function tool() {
	var title = encodeURIComponent(document.title);
	var url = encodeURIComponent(document.URL);

	// open window print panel
	$(".print").click(function(){
		window.print(); 
		return false;
	})
	
	// show social icon
	$(".save").toggle(function(){
		$(this).css({fontWeight:"bold"});
		$("#wrapper_links").fadeIn("slow");
		$(".delicious").attr( "href", "http://del.icio.us/post?url="+url+"&amp;title="+title);
		$(".google").attr( "href", "http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=&amp;title="+title);
		$(".digg").attr( "href", "http://digg.com/submit?phase=2&amp;url="+url+"&amp;title="+title);
		$(".stumble").attr("href", "http://www.stumbleupon.com/submit?url="+url+"&amp;title="+title);
	},function(){
	 		$(this).css({fontWeight:"normal"});
	 		$("#wrapper_links").slideUp("slow");
	});
	
	// populate input with current url
	$("#permanent_link").val(location.href);

	// select all text
	$("#permanent_link").focus(function(){
	   this.select();
	});
	
	// ============
	// = bookmark =
	// ============
	 
	// add a "rel" attrib if Opera 7+  
    if(window.opera) {  
        if ($("a.jqbookmark").attr("rel") != ""){ // don't overwrite the rel attrib if already set  
            $("a.jqbookmark").attr("rel","sidebar");  
        }  
    }  

    $("a.jqbookmark").click(function(event){  
        event.preventDefault(); // prevent the anchor tag from sending the user off to the link  
        var url = this.href;  
        var title = document.title;  

        if (window.sidebar) { // Mozilla Firefox Bookmark  
            window.sidebar.addPanel(title, url,"");  
        } else if( window.external ) { // IE Favorite  
            window.external.AddFavorite( url, title);  
        } else if(window.opera) { // Opera 7+  
            return false; // do nothing - the rel="sidebar" should do the trick  
        } else { // for Safari, Konq etc - browsers who do not support bookmarking scripts (that i could find anyway)  
             alert('Unfortunately, this browser does not support the requested action,'  
             + ' please bookmark this page manually.');  
        }  

    });
}

function cookie() {
	// footer state
   var footer = $.cookie('footer');
   // Set the user's selection for the footer
   if (footer == 'hide') {
			$("a.btn_open").show();      
			$("a.btn").hide();
			$(".wrapper_content_footer").css("display","none");	
   };

	// font size
	var font = $.cookie('font');
	if (font == 'narrow')
	$("body").addClass("narrow");
	else if (font == 'large')
	$("body").addClass("large");

// online service	
	// remember the state of box online service
	if ( $.cookie("online_service_hide") != null ){
		var pro_access_div = $.cookie("online_service_hide");
		var value_cookie = pro_access_div.split('|');
		var value="";
		$(value_cookie).each(function () {
			if(this!=""){
				value="."+this;
				$(value).hide();
				value_checkbox="#"+this;
				$(value_checkbox).attr('checked', false);
			 }
		 })
	}
}

function dropDown() {
	$(".footer .dropdown").hoverIntent(function(){
		$(this).find("li").show();
	},function(){
		$(".footer .dropdown ul li:not(:first-child)").hide();
	});
}
	
function closeMap(){
	 if ($("#modal:visible")) {
		 $("#modal, #wrapper_modal_content").hide();
	 };
}

function launchEdit () {
	$("#setting").bind('click', function() {
		// put the window in the right place
		var position = $(this).position();
		var position_left = $(".box_online").position();
		value_top = position.top;
		value_left = position_left.left;
		var bodyHeight = $("body").height();
		$("#modal").css({height:bodyHeight}).show();
		$("#wrapper_edit_mode").css({top:value_top, left:value_left}).show('slow');
		
		// give attribute to checkbox and class to label
		$(".edit_mode input:not(:checked)").each(function() {
	 		$(this).parents("label").addClass("disabled");
	 	});
	
		// action when you deselect box 
		if ($("#forpro_box:not(:checked)")) {
			$("#edit_for_pro").addClass("disabled_box");
		} else {
			$("#edit_for_pro").removeClass("disabled_box");
		}
		
		return false;
	});
}

function tooltipReadMe() {
	$(".read_me, .more_info").click(function() {
		var box = $(this).next("div");
		$(box).removeClass("hide");
		$(box).bind('mouseleave', function() {
			$(box).addClass("hide");
		});
		return false;
	});
}

function enable_edits() {
	// action when you click on checkbox
	$('.edit_mode :checkbox').click(function() {
		if ( $(this).parents("label").hasClass("disabled") ) {
			$(this).parents("label").removeClass('disabled');
		} else {
			$(this).parents("label").addClass('disabled');
		}
	});
	
	// action when you save iframe access
	$("#wrapper_edit_mode .active").bind("click",function(){
		// collect the id to hide the correspondant class 
		var bloc_pro_access="";
		$(".chk_target_block").each(function(){
			//looping through checkboxes
			var id=$(this).attr("id");
			if($(this).get(0).checked){
				$("."+id).show();
				bloc_pro_access.replace(id+"|", "");
			} else {
				$("."+id).hide();
				bloc_pro_access+=id+"|";	
			}
			$.cookie('online_service_hide', bloc_pro_access, { expires: 365, path: '/'});
		});
		
		$("#modal, #wrapper_edit_mode").hide();
		return false;
	});

	//action when you clic on setting in edit mode
	$("#setting_edit").bind('click', function() {
		$("#modal, #wrapper_edit_mode").hide();
		return false;
	});
	
	// action when you click on cancel
	$("#cancel_iframe").bind('click', function() {
		$("#modal, #wrapper_edit_mode").hide();
		return false;
	});
	
	// action when you click on reset setting
	$("#reset").bind('click', function() {
		$(".edit_mode input:checkbox").attr('checked','true');
		$(".edit_mode  label").removeClass('disabled');
		return false;
	});	
}

function launchOnlineService () {
	$(".btn_online_service").click(function() {
		$("#modal").show();
		$("#wrapper_big_nav").show();
		$("#wrapper_big_nav").load("big_nav.html",launchLocatorFromNav );
	});
}

function launchLocatorFromNav () {
	$(".call_locator").click(function() {
		$("#wrapper_big_nav").hide();
		$("#wrapper_modal_content").show();
		$("#wrapper_modal_content").load("/01/Modules/Fortis_BusinessLocator_ModuleTemplates/BusinessLocatorRedirection.aspx?redirect=1");
	});
}

// function launchDirectOnlineService () {
// 	$(".launchDirectOnlineService").click(function() {
// 		alert("toto");
// 	});
// }

//Functions for sitestat softclick

//Softclick function as from sitestat document
function ns_onclick(i, b, c, h, j) { var e = ""; if (typeof ns_pixelUrl == "string") { e = ns_pixelUrl.substring(0, ns_pixelUrl.indexOf("?") + 1) } e += c; e += "&ns_type=" + h + "&ns_action=view"; e += "&ns__t=" + (new Date()).getTime(); if (!b) { b = i.href } var d = document.referrer; if (d.lastIndexOf("/") == d.length - 1) { d = d.substring(d.lastIndexOf("/"), 0) } if (d.length > 0) { e += "&amp;ns_referrer=" + escape(d) } j = j || ""; var f = (i && i.target && i.target != "") ? (i.target.substring(0, 1) == "_") ? i.target.substring(1) : i.target : "self"; var g = new Image(); if (f && b) { if (window[f]) { window.ns_softclick_timer = function(k, a) { return function() { if (window.ns_softclick_timeout) { window.clearTimeout(window.ns_softclick_timeout) } g.onload = g.onerror = function() { return }; window[((window[k]) ? k : "self")].location.href = a } } (f, b); ns_softclick_timeout = window.setTimeout("ns_softclick_timer()", 5000); g.onload = g.onerror = window.ns_softclick_timer } else { window.open(b, f, j) } } g.src = e; return false };
//Replace links to documents
//function documentLinksToSoftClick()
//{  /$("a[href$='.pdf'],a[href$='.doc'],a[href$='.docx'],a[href$='.xls'],a[href$='.xlsx'],a[href$='.rtf']").click(function(){
//ns_onclick($(this)[0],'',$(this).attr("href"),'pdf');return false;
//});}

function documentLinksToSoftClick() {
    $("a[href$='.pdf'],a[href$='.doc'],a[href$='.docx'],a[href$='.xls'],a[href$='.xlsx'],a[href$='.rtf']").bind('click', function() {
        var docname = $(this).attr("href").toLowerCase().replace('/01/MyDocuments/', '').replace('/01/MyImages/', '');
        ns_onclick($(this)[0], '', docname, 'pdf');
        return false;
    });
}
