// Last updated 12/05/2010 by Aurelien

// NBE1.5 Main navigation sub menu display handler

// Following variables should be on each CiG pages
// var belongsto = "main menu item if page belongs to one in particular";
// var isprivate = true|false;
// var locale = "xx_XX";

window.name = "cigmain";

// PWP root for locale without unique language
var pwproot = {
                de_AT: "www.canon.at",
                de_DE: "www.canon.de",
                en_GB: "www.canon.co.uk",
                en_IE: "www.canon.ie",
                fr_BE: "fr.canon.be",
                fr_CH: "fr.canon.ch",
                fr_FR: "www.canon.fr",
                fr_LU: "www.canon.lu",
                nl_BE: "nl.canon.be",
                nl_NL: "www.canon.nl"
              };
              
// Authorize error page
var autherror = "/error/authorization.html";

// Getting the customer type
var p4 = getCookie('p4'); // Get and store p4
var pageCountry = locale.substr(3,2);
var mt_atr_val = ((parseInt(p4,16) >> 2) & 3); // Member type
var mtnav = ["none","cam","ij","all"];
var sc_atr_val = (parseInt(p4,16) & 3); // Service control
// Check user is logged in
var cigcontent = (getCookie('cigcontents') === 'ok') ? true : false ; // Check there is a cigcontent cookie equal to ok
var sso = (getCookie('crmSession')) ? true : false; // Check there is an SSO cookie with value
var isFromDJ = (getParamValue('from')) ? true : false; // Is customer coming from DJ page?

$(document).ready(function() {
dcsMultiTrack('DCS.dcsuri','/mttracking.html','WT.ti','Member Type Tracking','DCSext.membertype',mtnav[mt_atr_val],'DCSext.memberlocale',getCookie("p5")); // Send customer type and locale to WebTrends
  // Customise main navigation (div#main-menu) and top navigation (div#top-navigation) based on user type and log in status
  // Customise based on user type and log in status
  $(".main-menu-cam,.main-menu-ij,.main-menu-all").hide(); // Treats every customer as logged out by default
  // Then let's look if the customer is actually logged in
  if (cigcontent && sso) {
    if (!p4 && isprivate) {
      goDirectJump(); // If there is no p4 cookie on a private page, the customer shouldn't be there and needs to log in again. 
    }
    hideLinks(mtnav[mt_atr_val]); // Remove "duplicated" unecessary main-menu links for logged in customers
    $("li.loggedoutlinks").remove();// Remove links if customer is logged in
    $("li.loggedinlinks").removeClass("loggedinlinks");// Show links for logged in customers only
    $("#logobox a").attr('href','/pe/f/gateway.do?s=%2ftopPage');
    $("#top-navigation li:first a").attr('href','/pe/f/gateway.do?s=%2ftopPage');
  }
  else {
    if (isprivate || isFromDJ) { goDirectJumpWithFrom(); }
  }  

  // Replaces all XX in URLs by YY where YY is actually country code for customer. This will only happen for pages that are language based (e.g. articles) as opposed to locale based pages such as VPS pages
  if (pageCountry == "XX") {
    var p5 = getCookie("p5"); // We need p5 cookie value so let's get it and store it
    if (!p5) {
      goDirectJump(); // If there is no p5 cookie, the customer shouldn't be there and needs to log in again. 
    }
    var country = p5.substr(3,2); // Get the customer country from p5 cookie. 
    var language = p5.substr(0,2); // Get the customer language from p5 cookie. 
    $.each($("a"), function() {
      if ($(this).attr('href')) {
        $(this).attr('href',$(this).attr('href').replace(/www.canon.xx/ig,pwproot[p5]));
        $(this).attr('href',$(this).attr('href').replace(/[a-z]{2}_XX/ig,p5));
        $(this).attr('href',$(this).attr('href').replace(/[a-z]{2}-XX/ig,language + "-" + country));
      }
    });
  }

  // Highlight section current page belongs to...
  if (belongsto != "none") { $("a#main-menu-" + belongsto).addClass("main-menu-active"); }

  // Positions submenu below corresponding main menu item and applies main menu item bottom border color as background color for submenu
  $("#main-menu dt").each(function() {
    $(this).next("dd").css("left",$(this).position().left).css("background-color",$(this).css("border-bottom-color"));
  });
  
  // Sub-menu display control
  $("#main-menu dt a").click(function() {
    if ($(this).parents("dt").next("dd").is(":hidden")) {
      $("#main-menu dd").fadeOut("fast");
      $(this).parents("dt").next("dd").slideDown("fast");
    }
    else {
      $(this).parents("dt").next("dd").fadeOut("fast");
    }
    return false;
  });
  $("body").click(function() {
    $("#main-menu dd:visible").fadeOut("fast");
  });   
  
});

// Get Member type and Service control variables - reimplementation of authorize.js logic
// Settings
var mt_cam = sc_pa = [0,1,0,1];
var mt_ijm = sc_pb = [0,0,1,1];
// Member type
var CAM = mt_cam[mt_atr_val];
var IJM = mt_ijm[mt_atr_val];
// Service control
var PA = sc_pa[sc_atr_val];
var PB = sc_pb[sc_atr_val];

// hideLinks - Remove links from main menu based of customer's profile
function hideLinks(type) {
  switch (type) {
    case "cam": 
      $(".main-menu-cam + .main-menu-default, .main-menu-all + .main-menu-default, .main-menu-ij").remove();
      $(".main-menu-cam,.main-menu-all").show();
      break;
    case "ij": 
      $(".main-menu-ij + .main-menu-default, .main-menu-all + .main-menu-default, .main-menu-cam").remove();
      $(".main-menu-ij,.main-menu-all").show();
      break;
    case "all": 
      $(".main-menu-default").remove();
      $(".main-menu-cam,.main-menu-ij,.main-menu-all").show();
      break;
    default:
      $(".main-menu-cam,.main-menu-ij,.main-menu-all").remove(); // Or take user to DJ page which might be the most correct things to do here...
   }
 }

// getCookie - Get the value of a given cookie
function getCookie(c_name) {
  if (document.cookie.length>0) {
    c_start=document.cookie.indexOf(c_name + "=");
    if (c_start!=-1) {
      c_start=c_start + c_name.length+1;
      c_end=document.cookie.indexOf(";",c_start);
      if (c_end==-1) c_end=document.cookie.length;
      return unescape(document.cookie.substring(c_start,c_end));
    }
  }
  return "";
}

// set Cookie - Create a cookie
function setCookie(c_name,value,expiredays) {
  var exdate=new Date();
  exdate.setDate(exdate.getDate()+expiredays);
  document.cookie=c_name+ "=" +escape(value)+ ";path=/" + 
  ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

// Lots of isSomething functions
function	isCameraMember() {
  if (CAM == 1 && IJM == 0) { return true; } else { return false; }
}
function	isPrinterMember() {
  if (CAM == 0 && IJM == 1) { return true; } else { return false; }
}
function	isPerfectMember() {
  if (CAM == 1 && IJM == 1) { return true; } else { return false; }
}
function	isCameraMemberOrPerfectMember() {
  if (CAM == 1) { return true; } else { return false; }
}
function	isPrinterMemberOrPerfectMember() {
  if (IJM == 1) { return true; } else { return false; }
}


// Lot of authorize functions
function	authorizeCameraMember() {
  if (isCameraMember()) { return true; } else { location.href = autherror; }
}
function	authorizePrinterMember() {
  if (isPrinterMember()) { return true; } else { location.href = autherror; }
}
function	authorizePerfectMember() {
  if (isPerfectMember()) { return true; } else { location.href = autherror; }
}
function	authorizeCameraMemberAndPerfectMember() {
  if (isCameraMemberOrPerfectMember()) { return true; } else { location.href = autherror; }
}
function	authorizePrinterMemberAndPerfectMember() {
  if (isPrinerMemberOrPerfectMember()) { return true; } else { location.href = autherror; }
}

// canDownloadCameraApplication - If CAM customer, we create a special cookie
function	canDownloadCameraApplication() {
	if ( CAM == 1 ) {
		document.cookie = "cameraapplication=ok; path=/";
	}	else {
		location.href = autherror;
	}
}

// canDownloadPrinterApplication - If IJM customer, we create a special cookie
function	canDownloadPrinterApplication() {
	if (IJM == 1) {
		document.cookie = "printerapplication=ok; path=/";
	}	else {
		location.href = autherror;
	}
}

// getParamValue - Given a parameter, will return the value of it in the location.search string
function getParamValue(paramName) {
  var allParams = {};
  if (location.search.length>0) {
    var queryString = location.search;
    queryString = queryString.slice(1).split("&");
    for (var params in queryString) {
      allParams[queryString[params].split("=")[0]] = unescape(queryString[params].split("=")[1]);
    }
    return allParams[paramName];
  }
  return "";
}

// goDirectJump - Takes customer to Direct Jump page for quick login to the page

function goDirectJump() {
  location.href = "https://" + location.host + "/pe/f/djReception.do?d=static&url="	+ encodeURIComponent(location.href);
}

function goDirectJumpWithFrom() {
  location.href = "https://" + location.host + "/pe/f/djReception.do?d=static&url="	+ encodeURIComponent(location.href) + "&from=" + getParamValue('from');
}

function cigmain()
{
	newWindow = window.open("","cigmain","");
	newWindow.focus();
	return newWindow;
}

function photoalbum()
{
	newWindow = window.open("","photoalbum","");
	newWindow.focus();
	return newWindow;
}

function ijppmain()
{
	newWindow = window.open("","ijppmain","width=1029,height=657,toolbar=no,locationbar=no,personalbar=no,menubar=no,scrollbars=yes,resizable=yes");
	newWindow.focus();
	return newWindow;
}
