// check if UA is IE
var ie =  (typeof window.ActiveXObject != 'undefined');

// for the simulator
var ctx;
var img;
var scale;

// for setting view options on CGI pages    
var url = location.href;

jQuery(document).ready(function($){
    if(url.indexOf("mt-search.cgi") != -1) {
       	if($.cookie("prefs")){
		    var cv=$.cookie("prefs");
		    var fs=cv.substring(cv.indexOf('fontSize')+8,cv.indexOf('fontSize')+9);
		    var ct=cv.substring(cv.indexOf('contrast')+8,cv.indexOf('contrast')+9);
		    var lt=cv.substring(cv.indexOf('layout')+6,cv.indexOf('layout')+7);
		}
		if(fs == "1"){ $("body").addClass("largeType");multinav(); }
		if(fs == "2"){ $("body").addClass("largerType");multinav(); }
		if(fs == "3"){ $("body").addClass("largestType");multinav(); }
		if(ct == "1"){ $("body").addClass("darkOnLight"); }
		if(ct == "2"){ $("body").addClass("lightOnDark"); }
    }
    multinav();
    $(".asset-listing .excerpt-text").autolink();
    $("ul.article-tools").prepend('<li class="first"><a href="#" class="icn-link print-link">print</a></li>');
    $("a.print-link").click(function() {
        window.print();
        return false;
    });
    $('a[href="#need-link"]').css("border-top","1px solid #f00");
    $('input[title!=""]').hint(); // add hint text to text fields using the 'title' attribute
        $("#site-tools").remove();
    	$("#toolbar li").click(function(){
    		if($.cookie("prefs")){
    		    var cv=$.cookie("prefs");
    		    var fs=cv.substring(cv.indexOf('fontSize')+8,cv.indexOf('fontSize')+9);
    		    var ct=cv.substring(cv.indexOf('contrast')+8,cv.indexOf('contrast')+9);
    		    var lt=cv.substring(cv.indexOf('layout')+6,cv.indexOf('layout')+7);
    		} else {
    		    var fs="1";
    		    var ct="1";
    		    var lt="1";
    		}
    		var opt = $(this).attr("id");
    		opt = opt.replace(/Control/,"");
    		var optClass = $(this).attr("class");
    		if(optClass == "type-ctl"){
    			$("body").removeClass("largeType largerType largestType");
    			$("body").addClass(opt);
    			$(".footer-column").css("height","auto");
    			$(".article-related .module").css("height","auto");
    			$(".home-column").css("height","auto");
                equalHeight($(".home-column"));
    			if(opt == "largeType"){ fs = "1"; }
    			if(opt == "largerType"){ fs = "2"; }
    			if(opt == "largestType"){ fs = "3"; }
    			multinav();
    		}
    		if(optClass == "layout-ctl") {
    			$("body").removeClass("singleColumn multiColumn");
    			$("body").addClass(opt);
    			if(opt == "multiColumn"){ lt = "1"; }
    			if(opt == "singleColumn"){ lt = "2"; }
    		}
    		if(optClass == "contrast-ctl") {
    		    $("body").removeClass("darkOnLight lightOnDark");
    		    $("body").addClass(opt);
    			if(opt == "lightOnDark") { var ct = "2"; }
    			if(opt == "darkOnLight") { var ct = "1"; }
    		}
    		$.cookie("prefs",null);
    		var cookieVals = "fontSize"+fs+"qcontrast"+ct+"qlayout"+lt;
    //        $.cookie("prefs",cookieVals, { expires: 7, path: "/", domain: ".grf.dev" });
    		$.cookie("prefs",cookieVals, { expires: 7, path: "/", domain: ".glaucoma.org" });
    		return false;
    	});
        //          $("#toolbar li a").hover(
        //             function(){
        //                 var tip = "<div id=\"SiteToolsHelp\" class=\"SiteToolsHelp\">"+this.innerHTML+"</div>";
        //                 $("body").append(tip);
        //                 var tipLeft = $(this).parent().position().left + 15;
        //                 var tipTop = $(this).parent().position().top + 30;
        //                 $("#SiteToolsHelp").css("left",tipLeft).css("top",tipTop);
        //             },
        //             function(){
        //                 $("#SiteToolsHelp").remove();
        //             }
        // );

	  $(".article-tools .email-link").add(".article-tools .email-send-pane .close").click(function(e){
	    e.preventDefault();
	    
	    if( $(this).parents("li").hasClass("active") ){
	      $(this).parents("li").removeClass("active");
	      $(".article-tools .email-send-pane").hide();
	    }else{
	      $(this).parents("li").addClass("active");
	      $(".article-tools .email-send-pane").show();
	    }
	  });
	  $(".article-tools .email-send-pane .btn-link").click(function(e){
	    e.preventDefault();
	    
	    var data = $(this).parents('form').serialize();
	    
	    data += "&page_source="+window.location.href;
	    
	    $.post('/script/email_friend.php?c=submit', data);

      $(".article-tools .email-send-pane").hide();
      $(".article-tools .email-send-pane input").val('');
      $(".article-tools .email-thanks-pane").show();
      setTimeout(function(){
        $(".article-tools .email-thanks-pane").parent('li').removeClass('active');
        $(".article-tools .email-thanks-pane").hide();
      },3000);
	  });
    $(".article-nav a").click(function(){
        var whichSection = $(this).attr("href");
        $(".article-nav a").removeClass("current");
        $(".article-section").removeClass("current");
        $("a[href="+whichSection+"]").addClass("current");
        if(whichSection=="#all"){
            $(".article-section").addClass("current");
            $(".entry-main").addClass("show-all");
        } else {
            $(".entry-main").removeClass("show-all");
            $(whichSection).addClass("current");
        }
        return false;
    });
    $("#carousel-nav a").click(function(){
       var whichItem = $(this).attr("href");
       $("#carousel-nav a").removeClass("active");
       $(".carousel-item").removeClass("active");
       $(this).addClass("active");
       $(whichItem).addClass("active");
       
       if( $(this).attr("href") == '#carousel-learn' ){
         startSlider();
       }
       return false;
    });
    if( $("#slider").size() ){
      $("#slider").slider({
        slide: sliderCanvasSlide
      });
      
      img = new Image();
//      img.src = "http://dev2.glaucoma.org/images/background.jpg";
      img.src = "http://www.glaucoma.org/images/background2.jpg";
    }
    if(document.location.hash){
      var whichSection = document.location.hash;
      $(".article-nav a").removeClass("current");
      $(".article-section").removeClass("current");
      $("a[href="+whichSection+"]").addClass("current");
      $(whichSection).addClass("current");
      var items = $(".article-top-nav li");
      var whichItem = $("a[href="+whichSection+"]").parents('li')[0];
      var thisItem = $.inArray(whichItem,items);
      adjustNextPrev($(".article-top-nav li").eq(thisItem));
    } else {
     adjustNextPrev($(".article-top-nav li").eq(0)); 
    }

    $(".article-top-nav li a").click(adjustNextPrev);
    $(".article-section-nav li a").click(adjustNextPrev);
    
});
function startSlider(){
  if( ie ){
    if( typeof G_vmlCanvasManager != 'undefined' ){
//      alert('good');
      G_vmlCanvasManager.initElement($("#canvas").get(0));
      
      ctx = $("#canvas").get(0).getContext('2d');
      sliderCanvasSlide();
    }else{
      setTimeout(startSlider,4000);
    }
  }else{
    ctx = $("#canvas").get(0).getContext('2d');
    sliderCanvasSlide();
  }
  
}
function sliderCanvasSlide(e,ui){
  if( ui ){ 
    var r = (100 - ui.value)*3;
  }else{
    var r = 300;
  }
  scale = (300 - r)/200;
  if( scale <= 0.04 )
    scale = 0.06;
  
  ctx.clearRect(0, 0, 280, 210);

  // background image in clipping region
  ctx.fillStyle = "#e4e3d4";
  ctx.fillRect(0, 0, 281, 211);
//  ctx.drawImage(img,7,7);//267,197
  ctx.drawImage(img,0,0);//267,197
    
  ctx.save();
  var circscale = r/80;
  if( circscale > 0.7125 ){
    ctx.save();
    ctx.beginPath();
    // translation to center it, include scale
    ctx.translate((280/2)-((100*circscale)/2),(210/2)-((100*circscale)/2));
    // scale to the proper size based on our slider
    ctx.scale(circscale,circscale);
    // this is to set up the black border around the circle
    ctx.moveTo(-150,-100);
    ctx.lineTo(50,-100);
    ctx.lineTo(50,0);
    // we're drawing a circle approximation with bezier curves
    // 0.55228475 is a best approximation the optimal control point locations
    // but it's based on a four-curve circle, it changes if you use more curves
    // to draw a better circle
    ctx.bezierCurveTo((50*0.55228475),0,0,(50*0.55228475),0,50);
    ctx.bezierCurveTo(0,50+(50*0.55228475),(50*0.55228475),100,50,100);
    ctx.bezierCurveTo(50+(50*0.55228475),100,100,50+(50*0.55228475),100,50);
    ctx.bezierCurveTo(100,(50*0.55228475),50+(50*0.55228475),0,50,0);
    // finish up here by drawing the rest of our border around the circle
    ctx.lineTo(50,-100);
    ctx.lineTo(250,-100);
    ctx.lineTo(250,200);
    ctx.lineTo(-150,200);
    ctx.lineTo(-150,-100);
    ctx.closePath();
    ctx.fillStyle = "black";
    ctx.fill();
    ctx.restore();
  }else{
    // just fill the whole thing with black when it gets too small
    ctx.fillStyle = "black";
    ctx.fillRect(0, 0, 281, 211);
  }
  ctx.restore();

  // if( scale >= 0.1 ){
  //   ctx.beginPath();
  //   ctx.save();
  //   ctx.translate(140-((126/2)*scale),60);
  //   ctx.scale(scale,scale);
  //   ctx.moveTo(modx(64),mody(29));
  //   ctx.bezierCurveTo(modx(73),mody(32),modx(86),mody(28),modx(95),mody(44));
  //   ctx.bezierCurveTo(modx(107),mody(67),modx(121),mody(55),modx(121),mody(55));
  //   ctx.bezierCurveTo(modx(132),mody(53),modx(123),mody(30),modx(109),mody(16));
  //   ctx.bezierCurveTo(modx(95),mody(2),modx(67),mody(0),modx(37),mody(0));
  //   ctx.bezierCurveTo(modx(7),mody(0),modx(0),mody(25),modx(0),mody(25));
  //   ctx.bezierCurveTo(modx(0),mody(33),modx(11),mody(41),modx(11),mody(41));
  //   ctx.bezierCurveTo(modx(25),mody(49),modx(27),mody(14),modx(64),mody(29));
  //   ctx.fillStyle = "black";
  //   ctx.fill();
  //   ctx.restore();
  // }
}
var startx = 140;
var starty = 105;
function modx(x){
  return x;
  //return startx+(x*scale);
}
function mody(y){
  return y;
  //return starty+(y*scale);
}
// function splitList(list){
//     
// }
function equalHeight(group) {
    tallest = 0;      
    group.each(function() {
        thisHeight = jQuery(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}
jQuery.fn.hint = function (blurClass) {
  if (!blurClass) { 
    blurClass = 'blur';
  }
  return this.each(function () {
    // get jQuery version of 'this'
    var $input = jQuery(this),
    // capture the rest of the variable to allow for reuse
      title = $input.attr('title'),
      $form = jQuery(this.form),
      $win = jQuery(window);

    function remove() {
      if ($input.val() === title && $input.hasClass(blurClass)) {
        $input.val('').removeClass(blurClass);
      }
    }
    // only apply logic if the element has the attribute
    if (title) { 
      // on blur, set value to title attr if text is blank
      $input.blur(function () {
        if (this.value === '') {
          $input.val(title).addClass(blurClass);
        }
      }).focus(remove).blur(); // now change all inputs to title
      // clear the pre-defined text when form is submitted
      $form.submit(remove);
      $win.unload(remove); // handles Firefox's autocomplete
    }
  });
};
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
jQuery.fn.autolink = function () {
    return this.each( function(){
        var re = /((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g;
        $(this).html( $(this).html().replace(re, '<a href="$1">$1</a> ') );
    });
}
function multinav(){
  var j=0;
  if (! jQuery(".article-top-nav").length) return;
  jQuery(".article-top-nav li").each( function( i, elem ) {
    if( i >= Math.ceil(jQuery(".article-top-nav li").size() / 2) ){
      jQuery(".article-top-nav li").eq(i).css({position: 'absolute',right: 0,top: (jQuery(".article-top-nav li").eq(i).outerHeight()*j)});
      j++;
    }	
  });
  //for( var i=0;i<$(".article-top-nav li").size();i++ ){    
  //}  
}
function adjustNextPrev(o){
  if( o.target ) // if this is a click from an anchor, get the parent li
    o = jQuery(o.target).parent();
  if( jQuery(o).parents(".article-section-nav").get(0) ){ // if this is actually a next/prev link, get the list element
    o = jQuery(".article-top-nav a[href="+jQuery(o).find("a").attr('href')+"]").parent();
  }
  
  if( jQuery(o).prev().size() ){
    jQuery(".article-section-nav .left a").text("« "+jQuery(o).prev().find("a").text()).attr('href',jQuery(o).prev().find("a").attr('href'));
  }else{
    jQuery(".article-section-nav .left a").html("&nbsp;").attr('href','#');
  }
  if( jQuery(o).next().size() && jQuery(o).next().get(0) != jQuery(".article-top-nav li:last").get(0) ){
    jQuery(".article-section-nav .right a").text(jQuery(o).next().find("a").text()+" »").attr('href',jQuery(o).next().find("a").attr('href'));
  }else{
    jQuery(".article-section-nav .right a").html("&nbsp;").attr('href','#');
  }
  jQuery(".article-section-nav .left a").removeClass('current');
  jQuery(".article-section-nav .right a").removeClass('current');
}
