/**
 * Disclaimer - Popup Page Disclaimer
 *
 * @version   1.0
 *
 *
 * @author    Chris Taylor (chris.taylor@morningstar.com)
 */
 var $jq = jQuery.noConflict();


 String.prototype.startsWith = function(str)
 {return (this.match("^"+str)==str)}

 function relContains(relString,relContains){ 
  var relArray;  
  var relLength;
  if (relString != undefined){
  relArray = relString.split(" ");
  relLength = relArray.length;
  }
  
  for (var i=0; i<relLength; i++){
   
   if (relArray[i].startsWith(relContains)){
    return relArray[i];
   }
  
  
  }
  return "";
}

 $jq.hsDisclaimer = function(options) {
  
  /* set the default options for hsDisclaimer */
  
  var defaults = {
      DisclaimerMessage:'Please set DisclaimerMessage', /* Message shown in disclaimer */
      DisclaimerMessage2:'Please set DisclaimerMessage', /* Message shown in second disclaimer (for two-step) */
      DisclaimerDiv:'', /* Div to use for disclaimer message */
      DisclaimerDiv2:'', /* Div to use for second disclaimer message (for two-step) */
      DisclaimerTextClass:'', /* Additional Class to use for disclaimer text */
      DisagreeMessage:'Please set DisagreeMessage', /* Message shown if UsesDisagreeMessage = true and user declines */
      UsesDisagreeMessage: false, /* Show a message if the user declines, otherwise do default action (link->don't like, page->back 1 page)
      CookieName: 'hsDisclaim', /* Name appended onto "hsDsisclaimer" to use for Cookie */
      DisableCookies: false, /* Turns off cookies, users have to answer each time */
      AcceptButtonText: 'I accept', /* Button used for "accept", or the country submit in a countrydisclaimer */
      AcceptButtonText2: 'I accept', /* Button used for "accept", on step 2 of 2-step */
      DeclineButtonText: 'I decline', /* Button used for "decline", or the country submit in a countrydisclaimer */
      DeclineButtonText2: 'I decline', /* Button used for "decline", on step 2 of 2-step */
      UseOverlay : true, /* Block out the background content of the page with an overlay */
      UseOverlayFades : true, /* Should the overlay fade in/out? can cause a brief period when content underneath is visible */      
      EmbargoedCountries: [], /* if we're using rel="hscountrydisclaimer", which are the disallowed countries */
      CountryList: ["Afghanistan","Albania","Algeria","Andorra","Angola","Antigua &amp; Deps","Argentina","Armenia","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bhutan","Bolivia","Bosnia Herzegovina","Botswana","Brazil","Brunei","Bulgaria","Burkina","Burundi","Cambodia","Cameroon","Canada","Cape Verdi","Central African Rep","Chad","Chile","China","Colombia","Comoros","Congo","Congo (Democratic Rep)","Costa Rica","Croatia","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","East Timor","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Ethiopia","Fiji","Finland","France","Gabon","Gambia","Georgia","Germany","Ghana","Greece","Grenada","Guatemala","Guinea","Guinea-Bissau","Guyana","Haiti","Honduras","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland (Republic)","Israel","Italy","Ivory Coast","Jamaica","Japan","Jordan","Kazakhstan","Kenya","Kiribati","Korea North","Korea South","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Mauritania","Mauritius","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro","Morocco","Mozambique","Myanmar (Burma)","Namibia","Nauru","Nepal","Netherlands","New Zealand","Nicaragua","Niger","Nigeria","Norway","Oman","Pakistan","Palau","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Qatar","Romania","Russian Federation","Rwanda","St Kitts &amp; Nevis","St Lucia","St Vincent &amp; Gr/dines","Samoa","San Marino","Sao Tome &amp; Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","Spain","Sri Lanka","Sudan","Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Togo","Tonga","Trinidad &amp; Tobago","Tunisia","Turkey","Turkmenistan","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States","Uruguay","Uzbekistan","Vanuatu","Vatican City","Venezuela","Vietnam","Yemen","Zambia","Zimbabwe"], /* list of all countries to show in the dropdown */
      AlignHorizontal: true,
      AlignVertical: true,
      AlwaysScroll: false,
      OpenInNewWindow: false
   };

  var options = $jq.extend({}, defaults, options); 
  var DiscCookieName = 'hsDisclaimerPage'+options.CookieName;
  
  /* sets a cookie */  
  setCookie = function(val){
   if (!options.DisableCookies){
    $jq.cookie(DiscCookieName,val);
   }
  }
  
  if (options.DisableCookies){
   /* Make sure no cookies are set already */
   setCookie(null);
  }
  
  /* Apply the disclaimers to links on the page, depending on their "rel" attribute */
  $jq(document).ready(function () {
  
   var disclaimerContent,disclaimerContent2;
   /* Set the content for the disclaimer - if a div is set, use the div's content, otherwise use the DisclaimerMessage */
   if (options.DisclaimerDiv != '') 
    { disclaimerContent = escape($jq('#'+options.DisclaimerDiv).html());}
    else 
    { disclaimerContent = escape(options.DisclaimerMessage); }
    
   if (options.DisclaimerDiv2 != '') 
    { disclaimerContent2 = escape($jq('#'+options.DisclaimerDiv2).html());}
    else 
    { disclaimerContent2 = escape(options.DisclaimerMessage2); }

    
   $jq("a[rel^='hsdisclaimer']").bind("click",function(e){ 
    if ($jq.cookie(DiscCookieName) != 'allow'){  
     var relTag = $jq(this).attr('rel');
     if (relTag.indexOf("::") > -1){        
        popupSimpleDisclaimer(this,options.UseOverlay,disclaimerContent,relTag.substring(relTag.indexOf("::")+2,relTag.indexOf(" ")));
     } else {
        popupSimpleDisclaimer(this,options.UseOverlay,disclaimerContent,'');
     }
    return false;
    }
    });
    $jq("a[rel^='hscountrydisclaimer']").bind("click",function(e){
    var relTag = $jq(this).attr('rel');
    if (relTag.indexOf("::") > -1){        
      popupCountryDisclaimer(this,options.UseOverlay,disclaimerContent,relTag.substring(relTag.indexOf("::")+2,relTag.indexOf(" ")));      
     } else {
      popupCountryDisclaimer(this,options.UseOverlay,disclaimerContent,'');
     }   
    return false;
   });
   $jq("a[rel^='hstwostepcountrydisclaimer']").bind("click",function(e){
    var relTag = $jq(this).attr('rel');
    if (relTag.indexOf("::") > -1){        
      popupTwoStepDualCountryDisclaimer(this,options.UseOverlay,disclaimerContent,disclaimerContent2,relTag.substring(relTag.indexOf("::")+2,relTag.indexOf(" ")));
         $jq(window).scroll(function(){
            centerThis('.hsdisclaimer');
     });       
     } else {
      popupTwoStepDualCountryDisclaimer(this,options.UseOverlay,disclaimerContent,disclaimerContent2,'');
         $jq(window).scroll(function(){
            centerThis('.hsdisclaimer');
     });       
     }   
    return false;
   });   
   if (relContains($jq('body').attr('rel'),'hsdisclaimer')) {
   if ($jq.cookie(DiscCookieName) != 'allow'){
    popupSimpleDisclaimer(null,options.UseOverlay,disclaimerContent);
         $jq(window).scroll(function(){
            centerThis('.hsdisclaimer');
     });  
   }
   }
   if (relContains($jq('body').attr('rel'),'hscountrydisclaimer')) {
   if ($jq.cookie(DiscCookieName) != 'allow'){
     popupCountryDisclaimer(null,options.UseOverlay,disclaimerContent,'');
          $jq(window).scroll(function(){
             centerThis('.hsdisclaimer');
     });  
   }
   }
   if (relContains($jq('body').attr('rel'),'hstwostepcountrydisclaimer')) {
   if ($jq.cookie(DiscCookieName) != 'allow'){
     popupTwoStepDualCountryDisclaimer(null,options.UseOverlay,disclaimerContent,disclaimerContent2,'');
          $jq(window).scroll(function(){
             centerThis('.hsdisclaimer');
     });  
   }
   }      
  });
  
  /* Standard Yes/No Disclaimer */
  popupSimpleDisclaimer = function(tag,overlay,message,linkurl) {
   var interactions;
   if (linkurl != '') {   
     var acceptLink = linkurl;
     } else {
     var acceptLink = $jq(tag).attr("href");
     }
if (tag!=null){     
   interactions ="<a href='"+acceptLink+"' rel='hsDisclaimerAccept'";
    if (options.OpenInNewWindow){
     interactions += 'target=\"_blank\"';
    }
    interactions += "onclick='setCookie(\"allow\");";
 if (options.OpenInNewWindow == true){
  
         interactions += "clearDisclaimer();";
        }    
    interactions += "'>"+options.AcceptButtonText+"</a> | <a href='#' onclick='doDisagreeAction(\"clear\")' rel='hsDisclaimerDecline'>"+options.DeclineButtonText+"</a>";   
    } else {
    interactions ="<a href='#' onclick='setCookie(\"allow\");clearDisclaimer();successState();return false;' class='disclaimerButton accept'>"+options.AcceptButtonText+"</a> | <a href='#' onclick='doDisagreeAction(\"back\")' rel='hsDisclaimerDecline' class='disclaimerButton reject'>"+options.DeclineButtonText+"</a>";
   }
    doShowOverlay(null);

   htmlStr = "<div class='hsdisclaimer'><div class='hsdisclaimertext "+ options.disclaimerTextClass +"'>"+unescape(message)+"<p>"+interactions+"</p></div></div>";
   $jq("body").append(htmlStr);   
   centerThis('.hsdisclaimer');
   $jq('.hsdisclaimer').fadeIn("slow", function(){centerThis('.hsdisclaimer');} )
   return false;
  };
  
  /* A "Select your country" Disclaimer */
  popupCountryDisclaimer = function(tag,overlay,message,linkurl) {
   if (linkurl != '') {   
     var acceptLink = linkurl;
     } else {
     var acceptLink = $jq(tag).attr("href");
     } 
     
   doShowOverlay(null);

   htmlStr = "<div class='hsdisclaimer'><div class='hsdisclaimertext "+ options.disclaimerTextClass +"'>"+unescape(message)+"</div><p>";
   htmlStr = htmlStr+ "<select id='disclaimerCountry'>";
   for (country in options.CountryList){
    htmlStr = htmlStr+ "<option value='"+options.CountryList[country]+"'>"+options.CountryList[country]+"</option>";
   }
   htmlStr = htmlStr+"<input type='button' id='countrybutton' value='"+options.AcceptButtonText+"' onclick='checkEmbargoedCountries(\""+tag+"\",\""+escape(acceptLink)+"\")'/>";
   htmlStr = htmlStr+"</select></p></div>";
   $jq("body").append(htmlStr);   
   centerThis('.hsdisclaimer');
   $jq('.hsdisclaimer').fadeIn("slow", function(){} )
   return false;
  }
  
  /* Function to check if selected country is allowed and do the required actions if it is */
  checkEmbargoedCountries = function(tag,linkurl){
   var selectedCountry = $jq('#disclaimerCountry').attr('value');
   var isAllowed = true;
   for (var i=0;i<options.EmbargoedCountries.length;++i){
    if (options.EmbargoedCountries[i] == selectedCountry){
      if (tag != "null") {
       doDisagreeAction("clear");
      }
      else {
       doDisagreeAction("back");
      }
      isAllowed = false;
    }     
   }
   if (isAllowed == true){    
     if (tag == "null") {
          clearDisclaimer();
          setCookie("allow");
        }
        else {
        if(options.OpenInNewWindow == false){
          window.location = unescape(linkurl);
          }
          else {
          window.open(unescape(linkurl),'disclaimerTarget');
          clearDisclaimer();
          }
          setCookie("allow");
         }
    }
  }
    
 /* A Dual "Select your country"/"place of origin" Disclaimer */
  popupDualCountryDisclaimer = function(tag,overlay,message,linkurl) {
   if (linkurl != '') {   
     var acceptLink = linkurl;
     } else {
     var acceptLink = $jq(tag).attr("href");
     } 
     
   doShowOverlay(null);                                                                     

   htmlStr = "<div class='hsdisclaimer'><div class='hsdisclaimertext "+ options.disclaimerTextClass +"'>"+unescape(message)+"</div><p>";
   htmlStr = htmlStr+"<p>Please confirm your country of residence:</p>"
   htmlStr = htmlStr+ "<select id='disclaimerCountry'>";
   for (country in options.CountryList){
    htmlStr = htmlStr+ "<option value='"+options.CountryList[country]+"'>"+options.CountryList[country]+"</option>";
   }
   htmlStr = htmlStr+"</select>";
   htmlStr = htmlStr+"<p>Please confirm the country you are currently located in:</p>";
   htmlStr = htmlStr+ "<select id='disclaimerLocation'>";
   for (country in options.CountryList){
    htmlStr = htmlStr+ "<option value='"+options.CountryList[country]+"'>"+options.CountryList[country]+"</option>";
   }
   htmlStr = htmlStr+"</select>";   
   htmlStr = htmlStr+"<input type='button' id='countrybutton' value='"+options.AcceptButtonText+"' onclick='checkDualEmbargoedCountries(\""+tag+"\",\""+acceptLink+"\")'/>";
   htmlStr = htmlStr+"</p></div>";
   $jq("body").append(htmlStr);   
   centerThis('.hsdisclaimer');
   $jq('.hsdisclaimer').fadeIn("slow", function(){} )   
   return false;
  }  
  
  /* Function to check if dual selected countries are allowed and do the required actions if it is */
  checkDualEmbargoedCountries = function(tag,linkurl){
   var selectedCountry = $jq('#disclaimerCountry').attr('value');
   var selectedCountry2 = $jq('#disclaimerLocation').attr('value');
   var isAllowed = true;
   for (var i=0;i<options.EmbargoedCountries.length;++i){
    if (options.EmbargoedCountries[i] == selectedCountry || options.EmbargoedCountries[i] == selectedCountry2){
      if (tag != "null") {
       doDisagreeAction("clear");
      }
      else {
       doDisagreeAction("back");
      }
      isAllowed = false;
    }     
   }
   if (isAllowed == true){    
     if (tag == "null") {
          clearDisclaimer();
          setCookie("allow");
        }
        else {
          window.location = linkurl;
          setCookie("allow");
         }
    }
  }  
  

 /* Two Step (country->yes no) Disclaimer */
  popupTwoStepDualCountryDisclaimer = function(tag,overlay,message,message2,linkurl) {
   if (linkurl != '') {   
     var acceptLink = linkurl;
     } else {
     var acceptLink = $jq(tag).attr("href");
     } 
     
   doShowOverlay(null);

   htmlStr = "<div class='hsdisclaimer'><div class='hsdisclaimertext "+ options.disclaimerTextClass +"'>"+unescape(message)+"</div><p>";
   htmlStr = htmlStr+"<p>Please confirm your country of residence:</p>"
   htmlStr = htmlStr+ "<select id='disclaimerCountry'>";
   for (country in options.CountryList){
    htmlStr = htmlStr+ "<option value='"+options.CountryList[country]+"'>"+options.CountryList[country]+"</option>";
   }
   htmlStr = htmlStr+"</select>";
   htmlStr = htmlStr+"<p>Please confirm the country you are currently located in:</p>";
   htmlStr = htmlStr+ "<select id='disclaimerLocation'>";
   for (country in options.CountryList){
    htmlStr = htmlStr+ "<option value='"+options.CountryList[country]+"'>"+options.CountryList[country]+"</option>";
   }
   htmlStr = htmlStr+"</select><br/><br/>";   
   htmlStr = htmlStr+"<input type='button' id='countrybutton' value='"+options.AcceptButtonText+"' onclick='checkDualTwoStepEmbargoedCountries(this.parentNode,\""+tag+"\",\""+overlay+"\",\""+message+"\",\""+message2+"\",\""+acceptLink+"\")'/>";
   htmlStr = htmlStr+"</p></div>";
   $jq("body").append(htmlStr);   
   centerThis('.hsdisclaimer');
   $jq('.hsdisclaimer').fadeIn("slow", function(){} )   
   return false;
  }  
  
  
  /* Function to check if dual selected countries are allowed and do the required actions if it is */
  checkDualTwoStepEmbargoedCountries = function(div,tag,overlay,message,message2,linkurl){
   var selectedCountry = $jq('#disclaimerCountry').attr('value');
   var selectedCountry2 = $jq('#disclaimerLocation').attr('value');
   var isAllowed = true;
   for (var i=0;i<options.EmbargoedCountries.length;++i){
    if (options.EmbargoedCountries[i] == selectedCountry || options.EmbargoedCountries[i] == selectedCountry2){
      if (tag != "null") {
       doDisagreeAction("clear");
      }
      else {
       doDisagreeAction("back");
      }
      isAllowed = false;
    }     
   }
   if (isAllowed == true){    
     if (tag == "null") {
          options.disclaimerTextClass = "hsdisclaimertext2";
          options.AcceptButtonText = options.AcceptButtonText2;
          options.DeclineButtonText = options.DeclineButtonText2;

          popupSimpleDisclaimer(null,overlay,message2,linkurl);
          
          clearDisclaimerBox(div);          
          centerThis('.hsdisclaimer');          
        }
        else {
          options.disclaimerTextClass = "hsdisclaimertext2";
          options.AcceptButtonText = options.AcceptButtonText2;
          options.DeclineButtonText = options.DeclineButtonText2;
          popupSimpleDisclaimer(tag,overlay,message2,linkurl);
          
          clearDisclaimerBox(div);          
          centerThis('.hsdisclaimer');          
         }
    }
  }   
  /* Callback function */
  successState = function(){}
  
  /* Remove the disclaimer box/overlay from the page */
  clearDisclaimer = function(){  
  $jq('.hsdisclaimer').fadeOut("slow", function(){$jq('.hsdisclaimer').remove();} )
  if ($jq('.hsdisclaimeroverlay')){
      doHideOverlay();
   }  
  }

  clearDisclaimerBox = function(div){
   $jq(div).fadeOut("slow", function(){$jq(div).remove();} ) 
   centerThis('.hsdisclaimer');   
  }  


 /* This is what happens if the user declines... */
 doDisagreeAction = function(action){
   setCookie(null);
   if (action == 'clear'){
    if (options.UsesDisagreeMessage){
     $jq('.hsdisclaimer').html(options.DisagreeMessage)
    } else {
     clearDisclaimer();
    }
    return false;
   }
   if (action == 'back'){
    if (options.UsesDisagreeMessage){
     $jq('.hsdisclaimer').html(options.DisagreeMessage)
    }  
    else {    
     history.go(-1);
    }
    return false;
   }  
   
  }
  

  
  /* calculates the central area on the page */
  function centerThis(div) {
    var arrPageSizes = getPageSize();    
    var winH = $jq(window).height();
    var winW = $jq(window).width();
    $jq(div).each(function(){
     if(options.AlignVertical){
     $jq(this).css('top', winH/2-$jq(this).height()/2+$jq(window).scrollTop());
     }
     else {
     alert("hi");
     $jq(this).css('top', "20px");
     }
     if(options.AlignHorizontal){
     $jq(this).css('left', winW/2-$jq(this).width()/2)
     }
     
     }
    );    
  };
  
  /* shows the overlay (if enabled) */
  doShowOverlay = function(settings){
    $jq("body").addClass("disclaimer_body");  
    $jq("body").css("overflow-x","hidden");  
  if(options.UseOverlay){
    $jq('embed, object, select').css({ 'visibility' : 'hidden' });

    $jq("body").append("<div class='hsdisclaimeroverlay'></div>");
    var arrPageSizes = getPageSize();    
    $jq('.hsdisclaimeroverlay').css({
      width:        arrPageSizes[0],
      height:       arrPageSizes[1]  + 200
      })
      if(options.useOverlayFades){
      $jq('.hsdisclaimeroverlay').fadeIn();  
      }
      else
      {
      $jq('.hsdisclaimeroverlay').show();  
      }
      $jq(window).resize(function(){
        var arrPageSizes = getPageSize();    
        $jq('.hsdisclaimeroverlay').css({
          width:        arrPageSizes[0],
          height:       arrPageSizes[1]
        });
        centerThis('.hsdisclaimer');
      });
     } else {
     $jq(window).resize(function(){
        centerThis('.hsdisclaimer');
     });   
     $jq(window).scroll(function(){        
        centerThis('.hsdisclaimer');
     });        
    }
    if(options.AlwaysScroll){
     $jq(window).scroll(function(){
        centerThis('.hsdisclaimer');
     });     
    }
    
  }
  
  /* hides the overlay (again, if enabled) */
  doHideOverlay = function(){
  
   if(options.UseOverlay){
   $jq('embed, object, select').css({ 'visibility' : 'visible' });
    if(options.useOverlayFades){
         $jq('.hsdisclaimeroverlay').fadeOut(function() { $jq('.hsdisclaimeroverlay').remove(); });
         }
         else
         {
         $jq('.hsdisclaimeroverlay').hide().remove();  
      }
      
    } 
  $jq("body").removeClass("disclaimer_body");    
  $jq("body").css("overflow-x","auto");      
  }
  
  /* calculates the scrolling size of the page */
  getPageSize = function()  {
        var xScroll, yScroll;
        if (window.innerHeight && window.scrollMaxY) {  
          xScroll = window.innerWidth + window.scrollMaxX;
          yScroll = window.innerHeight + window.scrollMaxY;
        } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
          xScroll = document.body.scrollWidth;
          yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
          xScroll = document.body.offsetWidth;
          yScroll = document.body.offsetHeight;
        }
        var windowWidth, windowHeight;
        if (self.innerHeight) { // all except Explorer
          if(document.documentElement.clientWidth){
            windowWidth = document.documentElement.clientWidth; 
          } else {
            windowWidth = self.innerWidth;
          }
          windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
          windowWidth = document.documentElement.clientWidth;
          windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
          windowWidth = document.body.clientWidth;
          windowHeight = document.body.clientHeight;
        } 
        // for small pages with total height less then height of the viewport
        if(yScroll < windowHeight){
          pageHeight = windowHeight;
        } else { 
          pageHeight = yScroll;
        }
        // for small pages with total width less then width of the viewport
        if(xScroll < windowWidth){  
          pageWidth = xScroll;    
        } else {
          pageWidth = windowWidth;
        }
        arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
        return arrayPageSize;
      };
};

