/**
* hoverIntent r6 // 2011.02.26 // jQuery 1.5.1+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne brian(at)cherne(dot)net
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev])}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev])};var handleHover=function(e){var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t)}if(e.type=="mouseenter"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob)},cfg.timeout)}}};return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover)}})(jQuery);

// favicon changeing utility
var favicon = {
change: function(iconURL) {if (arguments.length==2) {document.title = optionalDocTitle;}this.addLink(iconURL, "icon");this.addLink(iconURL, "shortcut icon");},
addLink: function(iconURL, relValue) {var link = document.createElement("link");link.type = "image/x-icon";link.rel = relValue;link.href = iconURL;this.removeLinkIfExists(relValue);this.docHead.appendChild(link);},
removeLinkIfExists: function(relValue) {var links = this.docHead.getElementsByTagName("link");for (var i=0; i<links .length; i++) {var link = links[i];if (link.type=="image/x-icon" && link.rel==relValue) {this.docHead.removeChild(link);return;}}}, 
docHead:document.getElementsByTagName("head")[0]
}

var jQ=jQuery.noConflict();
// US only ....................................................................................
// panel_color_theme is defined in TS
// test if we stored the color in cookie
if(typeof(panel_color_theme) != "undefined" && getCookie("panel_color")){
  panel_color_theme = getCookie("panel_color");
}
if(typeof(panel_color_theme) != "undefined" && panel_color_theme){
  setLayoutColor(panel_color_theme);
}
// US only ....................................................................................

jQ(function() {
  jQ.fn.slider=function(options) {
    var settings=jQ.extend({ 
      show:1,
      pagination: false
    },options || {})
    return this.each(function() {
      var $this=jQ(this), $li=jQ('>li', $this), itemNr=$li.size(), lis='',items=settings.show,
      itemWidth=settings.width+parseInt($li.css('padding-right'))+parseInt($li.css('padding-left')),  
      sliderSize=itemNr*itemWidth, $left, $act,paginate=settings.pagination;
      $this.width(sliderSize).css('left',0).wrap('<div id="slider_'+this.id+'" class="slider"><div id="sliderCanvas_'+this.id+'" class="sliderCanvas"></div></div>');
      var mainCont=$this.parents('.slider:first'),ind=0;  
      mainCont
        .prepend('<div class="cArrows prev"></div>') 
        .append('<div class="cArrows next"></div>');
      if(mainCont.parents('.partnerSlider').length) mainCont=$this.parents('.partnerSlider:first')
      jQ('.prev',mainCont).addClass('disabled');
      if(itemNr==1) jQ('.next',mainCont).addClass('disabled')
      
      jQ('.prev',mainCont).click(function() { 
        $left=parseInt($this.css('left'));
        if($this.is(':not(":animated")') && $left!=0)  { $this.animate({left:$left+itemWidth},542,function() { 
          var $leftAft=parseInt($this.css('left'));
          jQ('.prev,.next',mainCont).removeClass('disabled')
          if($leftAft==0)  jQ('.prev',mainCont).addClass('disabled')
          else if($leftAft==-(sliderSize-(items*itemWidth))) jQ('.next',mainCont).addClass('disabled');
          if(paginate) jQ('.jumpTo li.active').removeClass('active').prev('li').addClass('active')
          ind--
        })}
        
        var jumpTo=jQ('.jcarousel-container .jumpTo',mainCont);
        if(jumpTo.length) {
          var size=jQ('li',jumpTo).length,pos=ind>size?size-5:ind;
          jQ("#partnersThumbnails").jcarousel('scroll',pos);
        }  
      });
      jQ('.next',mainCont).click(function() { 
        $left=parseInt($this.css('left'));
        if($this.is(':not(":animated")') && $left!=-(sliderSize-(items*itemWidth))) { $this.animate({left:$left-parseFloat(itemWidth)},542,function() { 
          var $leftAft=parseInt($this.css('left'));
          jQ('.prev,.next',mainCont).removeClass('disabled')
          if($leftAft==0) jQ('.prev',mainCont).addClass('disabled')
          else if($leftAft==-(sliderSize-(items*itemWidth))) jQ('.next',mainCont).addClass('disabled');
          if(paginate) jQ('.jumpTo li.active').removeClass('active').next('li').addClass('active')
          ind++
        })}
        if(jQ('.jcarousel-container .jumpTo',mainCont).length) {
          var pos=ind+2;
          jQ("#partnersThumbnails").jcarousel('scroll',pos);
        }  
      });
      if(paginate) {
        mainCont.append('<ul class="jumpTo"></ul>')
        for(i=0;i<itemNr;i++) {
          lis+='<li><a href="javascript:void(0)">&nbsp;</a></li>'
        }
        jQ('.jumpTo',mainCont).append(lis);
        jQ('.jumpTo li:first',mainCont).addClass('active');
      }
      jQ('.jumpTo li',mainCont).click(function() {          
          jQ(this).addClass('active').siblings().removeClass('active');
          var nr=jQ('.jumpTo li').index(jQ(this));
          if($this.is(':not(":animated")')) $this.animate({left:-(nr*itemWidth)},542,function() {
            var $leftAft=parseInt($this.css('left'));
            jQ('.disabled',mainCont).removeClass('disabled');
            if($leftAft==0) { jQ('.prev',mainCont).addClass('disabled') }
            else if($leftAft==-sliderSize+parseInt(items*itemWidth)) { jQ('.next',mainCont).addClass('disabled') }
          });    
      });
    });
  };
  jQ('#slider').slider({pagination:true,width:946});  
  jQ('#slider2').slider({width:199});
  jQ('#slider3').slider({width:579});
  jQ('#slider4').slider({width:567});
  jQ('#list li:odd').not('#list.newsList li:odd').addClass('odd');
  jQ('#list li:last-child').addClass('lastLi');
  
  
  /*POPUP*/
  var popupH=jQ('#popup').height(),popupPos=parseInt(popupH)/2,wHeight=jQ('html').height(),scroll=jQ('body')[0].scrollHeight,
  $pU=jQ('#popup').css('margin-top',-popupPos),overlay=jQ('#pageOverlay').height(scroll+wHeight)
  jQ('#signUp1,#signUp2').click(function() {    
    jQ("#slider").hide();
    $pU.show();overlay.show();
    
  })
  jQ('#popup .close').click(function() {
    $pU.hide();overlay.hide();
    jQ("#slider").show();
  });
  
  jQ('.toggleLink').click(function() {
    jQ(this).next('.collapsable').slideDown()
  })
  jQ('.collapsable .close').click(function() {
    jQ(this).parents('.collapsable').slideUp()
  })
  
  jQ('#signIn input').each(function() {
    var init=this.value;
    jQ(this).focus(function() {val=this.value;if(val==init) jQ(this).val('');}).blur(function() {val=this.value;if(val=="") jQ(this).val(init);});
  });
  jQ('.navBar #user_name').hoverIntent({  
    over: function() { 
      jQ('#userOptionsBox').slideDown()
    },
    timeout:100,
    interval:0,
    out: function() { jQ('#userOptionsBox').slideUp() } 
  });        
});  
// user timeout
var idleTime = 0;
// used by polldaddy
var htmlContentOfPoll = "";
var intervalToCheckPoll1,intervalToCheckPoll2 = null;
/**
 * test if polldaddy box has changed
 */
function changePollColorsIfNeeded(){
  if(htmlContentOfPoll != jQ("#quickPollBox").html()){
    switchThemeForPolls(typeof(panel_color_theme) != "undefined" ? panel_color_theme : "pink");
    htmlContentOfPoll = jQ("#quickPollBox").html();    
  }
}
jQ(document).ready(function () {  
  // used in case ajax crashes
  jQ(document).ajaxError(function() {
    if(jQ.isFunction(jQ.fn.dialog) && jQ("#loadingDiv").dialog("isOpen")){
      hideLoadingDialog();
      //alert("An internal error occured, please try again later!");
    }
  });
  //workaround  remove anchor from share box
  jQ("#c357,#c914,#c1186").remove();
  
    //Increment the idle time counter every minute.
    var idleInterval = setInterval("timerIncrement()", 60000); // 1 minute

    //Zero the idle timer on mouse movement.
    jQ(this).mousemove(function (e) {
        idleTime = 0;
    });
    jQ(this).keypress(function (e) {
        idleTime = 0;
    });
  /*add google +1 after each H1 element*/
  //jQ("h1").append('<span style="margin-left:10px"><g:plusone size="medium"></g:plusone></span>');    
  // Add social media buttons after each h1 TAG
	// facebook
	if(typeof(FACEBOOK_URL_TO_LIKE) == 'undefined'){
		FACEBOOK_URL_TO_LIKE = 'http://www.facebook.com/ValuedOpinionsUK';
	}	
	FACEBOOK_URL_TO_LIKE = 'http://' + document.location.host + document.location.pathname;
	var strFacebookLike = '<iframe src="//www.facebook.com/plugins/like.php?href=###URL###&amp;send=false&amp;layout=button_count&amp;width=100&amp;show_faces=true&amp;action=like&amp;colorscheme=light&amp;font&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px; height:21px;" allowTransparency="true"></iframe>';
	/*add google +1*/
	var strPlusOne = '<div id="plusone-div-###PLUS_ONE_INDEX###" class="plusone"></div>';
	var htmlSocialBtns = '<span class="socialMediaBtns">'+ strPlusOne + strFacebookLike + '</span>';
	htmlSocialBtns = htmlSocialBtns.replace('###URL###',FACEBOOK_URL_TO_LIKE);	
	
	// append social box to all h1 tags and assure G+ id's are unique
	jQ("h1").append(function(index, html) {
		return htmlSocialBtns.replace('###PLUS_ONE_INDEX###',index + 1);
	});

	// use G+ with parsetags=explicit - hack for IE 8
	for(var i=1;i <= jQ("h1").size();i++){
		gapi.plusone.render('plusone-div-' + i,{"size": "medium", "count": "true"});
	}
	
	// Add social media buttons after each h1 TAG
  // US only ....................................................................................
  //modify the polldaddy styles according to the current theme  
  switchThemeForPolls(typeof(panel_color_theme) == "undefined" ? false : panel_color_theme);
  //console.log(jQ("PDS_Poll").size());
  // as no event could be attached to polldady changes use setInterval to change for modifications
  if(document.getElementById("quickPollBox") && typeof(panel_color_theme) != "undefined"){
    htmlContentOfPoll = jQ("#quickPollBox").html();
    jQ(".pds-vote-button,.pds-view-results").live("click",function(){
      intervalToCheckPoll1 = setInterval("changePollColorsIfNeeded();", 1000);
    });
    jQ(".pds-return-poll").live("click",function(){
      intervalToCheckPoll2 = setInterval("changePollColorsIfNeeded();", 100);
    });    
  }
  
  // modify the logo acc. to the panel_language which is set in TS
  if(typeof(panel_language) != "undefined" && panel_language == "es"){        
    jQ("div.logo").removeClass("logo").addClass("logoEs");
  }  
  // if other color then purple is stored in cookie
  if(typeof(panel_color_theme) != "undefined" && panel_color_theme != "purple"){
    switchIntroMovie(panel_color_theme,false);
  }
  jQ("#slider_slider .cArrows").remove();
  
  // color and language chooser
  jQ("#customizePage").hoverIntent({  
    over: function() { 
      jQ('#customizeSelectorOptions').slideDown()
    },
    timeout:100,
    interval:0,
    out: function() { jQ('#customizeSelectorOptions').slideUp() } 
  });    
  
  jQ("#siteLanguageChooser").hoverIntent({  
    over: function() { 
      jQ('#languageSelectorBox').slideDown()
    },
    timeout:100,
    interval:0,
    out: function() { jQ('#languageSelectorBox').slideUp() } 
  });    
  jQ("#siteColorChooser").hoverIntent({  
    over: function() { 
      jQ('#colorSelectorBox').slideDown()
    },
    timeout:100,
    interval:0,
    out: function() { jQ('#colorSelectorBox').slideUp() } 
  });  
  //header right boxes that exceed the background height fix
  //alert("CMS Team Debug : " + );
  jQ("#right div.box h2").each(function(i,item){
    //alert("CMS Team Debug : " + jQ(this).html().length);
    if(jQ(this).html().length > 26){
      jQ(this).height(40);
    }
    
  });
  changeCustomImages();
  // US only ....................................................................................
});

function showLoadingDialog(str){
  var strText = "Loading ...";
  if(typeof(str) == "string"){
    strText = str;
  }
  jQ('<div/>', {id: 'loadingDiv',text:strText}).appendTo('body');
  jQ( "#loadingDiv" ).dialog({
    height: 60,
    closeOnEscape: false,
    draggable: false,
    resizable: false,
    modal: true,
    open: function(event, ui) {
      jQ(".ui-dialog-titlebar",jQ(this).parent()).hide();
    }
  });  
}

function hideLoadingDialog(){
  jQ('#loadingDiv').dialog("destroy").remove();
}

function ismaxlength(obj){
  var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
  if (obj.getAttribute && obj.value.length>mlength)
  obj.value=obj.value.substring(0,mlength)
}
function timerIncrement() {
    idleTime = idleTime + 1;
    if (idleTime > 15) { // 15 minutes
    //var url = document.location.protocol+"//"+document.location.host+"/index.php?type=8200&action=check_user&no_cache=1";
    var url = document.location.href + "?type=8200&action=check_user&no_cache=1";
    // logout  
    jQ.getJSON(url,function(json){      
      if(typeof(json) == "object" &&  json != null){
        if(json.logged){
          document.location = json.redirect;          
        }
      }
    });
    }
}
/**
 * This function is used to change the skin(main css) of the website 
 */
function setLayoutColor(color,element){
  if(color){    
    panel_color_theme = color;
    jQ("#colorSelectorBox li").removeClass("selected");
    if(typeof(element) != "undefined"){
      jQ(element).addClass("selected");
    }else{
      jQ("#colorSelectorBox li:first").addClass("selected");
    }
    jQ("#globalStyle").attr("href","fileadmin/templates/styles/styles_us_"+color+".css");
    favicon.change("fileadmin/templates/skins/"+color+"/favicon.ico");
    switchThemeForPolls(color);
    switchIntroMovie(color,true);
    setCookie("panel_color", color,1);
    changeCustomImages();
  }else{
    jQ("#colorSelectorBox li:first").addClass("selected");
  }
}
/**
 * This function is used to change the skin(main css) of polls that are loaded from a 3-th party software
 */
function switchThemeForPolls(color){
  if(color){
    var base_host = document.location.protocol+"//"+document.location.host + "/";
    var hexColor = "";
    var buttonBack = "fileadmin/templates/skins/"+color+"/buttonRight.gif";
    
    switch(color){
      case "purple":
        hexColor = "#9B2488";
        break;
      case "blue":
        hexColor = "#32C5F3";
        break;
    }  
    
    jQ(".pds-view-results,.pds-share,.pds-return-poll").css("color",hexColor);  
    jQ(".pds-vote-button").css("background",'url("'+ base_host + buttonBack +'") repeat-x scroll left top #F2F2F2');
    jQ(".pds-vote-button").css("border",hexColor);
    
    if(typeof(panel_language) != "undefined"){
      switch(panel_language){
        case "es":
          jQ(".pds-vote-button span").text("Votar");
        break;
      }
      
    }
    // WORKAROUND
    // when the polldaddy vote , view results functions are used
    // this method is called through a setInterval to change the color dynamically
    // if the color match clear the intervals
    if(intervalToCheckPoll1 != null || intervalToCheckPoll2 != null){
      var pollColor = "";
      if(jQ(".pds-view-results").css("color")){
        pollColor = jQ(".pds-view-results").css("color");
      }else if(jQ(".pds-return-poll").css("color")){
        pollColor = jQ(".pds-return-poll").css("color");
      }
      if(pollColor && hexColor && rgb2hex(pollColor) == hexColor){
        //vote , view results
        clearInterval(intervalToCheckPoll1);
        // go back to poll
        clearInterval(intervalToCheckPoll2);
      }
    }
  }
}
function switchIntroMovie(color,bForce){  
  if(jQ('#sliderBox ul[id="slider"] li').size() <= 1){
    return false;
  }
  if(color == "blue"){
    jQ('#sliderBox ul[id="slider"] li').hide();
    jQ('#sliderBox ul[id="slider"] li:eq(1)').show();
  }else if(color == "pink"){
    jQ('#sliderBox ul[id="slider"] li').hide();
    jQ('#sliderBox ul[id="slider"] li:eq(2)').show();
  }else if(bForce){
    jQ('#sliderBox ul[id="slider"] li:eq(1)').hide();
    jQ('#sliderBox ul[id="slider"] li:eq(0)').show();
  }
}
/**
 * Utility functions
 */
function setCookie(c_name,value,exdays){
  var exdate=new Date();
  exdate.setDate(exdate.getDate() + exdays);
  var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString())+"; path=/";
  document.cookie=c_name + "=" + c_value;
}
function getCookie(c_name){
  var i,x,y,ARRcookies=document.cookie.split(";");
  for (i=0;i<ARRcookies.length;i++)
  {
    x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
    y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
    x=x.replace(/^\s+|\s+$/g,"");
    if (x==c_name)
    {
    return unescape(y);
    }
    }
}
function changeCustomImages(){
  jQ("img[src^='uploads/vop_custom/']").each(function(){
    var src = jQ(this).attr("src");
    var path = src.split(".");
    if(path.length == 2){
      pathName = path[0];
      fileExt = path[1];
      info = pathName.split("_");
      if(info.length > 2){
        info[info.length - 2] = panel_language;
        info[info.length - 1] = panel_color_theme;
        jQ(this).attr("src",info.join("_") + "." + fileExt);
      }
    }
  });
}
function hex(x) {
    return ("0" + parseInt(x).toString(16)).slice(-2);
}
function rgb2hex(rgb) {
  if(typeof(rgb) == "undefined"){
    return "";
  }
  var retVal = "";
  try{
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);    
    var retVal = "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
  }catch(e){
    
  }
    
    return retVal;
}
function trackEventBanner(){
  _gaq.push(['_trackEvent', 'Banner Clicks', 'November 2011 banner']);
  window.location = 'http://www.valuedopinions.co.uk/daily-competition/';
}
