var MAGIC_TEXT_DISABLED = 1;
var overlay;

$(document).ready(function(){
  overlay = new OverLight();
});
function parseURL(url) {
  out = new Array();
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    out[pair[0]] = pair[1];
  }
  return out;
} 
function getUrlVars(url){
  return url.split("?")[1];
}
function addToCart(){
  overlay.show();
  $.get( '/cart/add-item?pc=js', getUrlVars(this.href),_cartData);
  return false;
}
function _cartData(data){
  data = eval(data);
  if(data.status == 'success'){
    overlay.set_text(data.html,"Item Added");
    $('#cart-btn').show();
    blinkcartout();
  }
  if(data.status == 'fail'){
    checkCartStatus();
    overlay.set_text(data.html,"Item Added");
  }
  postAjax();
}

function checkCartStatus(){
  $.get( '/cart/add-item?pc=js', 'action=checkStatus',_cartStatus);
}

function _cartStatus(data){
  $('#cart-btn').hide();
  data = eval(data);
  if(data.items > 0){
    $('#cart-btn').show();
    blinkcartout();
  }else{
    $('#cart-btn').hide();
  }
}

function blinkcartin(){
  $('#cart-btn a').fadeTo(500,1,blinkcartout);
}
function blinkcartout(){
  $('#cart-btn a').fadeTo(500,0.3,blinkcartin);
}


function fixSlideShow(sin,sout,sopt){
	
  var h = $(sin).children('.description').html();
  $(sin).children('.description').html('');
  $(sin).children('.description').html(h);

  $(sin).children('.description').css({
    filter:"alpha(opacity=100)"
  });
  $(sin).children('.description').hide();
  $(sin).children('.description').show();
	
  var h = $(sout).children('.description').html();
  $(sout).children('.description').html('');
  $(sout).children('.description').html(h);

  $(sout).children('.description').css({
    filter:"alpha(opacity=100)"
  });
  $(sout).children('.description').hide();
  $(sout).children('.description').show();
}


// vertical positioning in the viewport

(function($){
  $.fn.vCenter = function(options) {
    var pos = {
      sTop : function() {
        return window.pageYOffset || document.documentElement && document.documentElement.scrollTop ||	document.body.scrollTop;
      },
      wHeight : function() {
        return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body.clientHeight;
      }
    };
    return this.each(function(index) {
      if (index == 0) {
        var $this = $(this);
        var elHeight = $this.height();
        var elTop = pos.sTop() + (pos.wHeight() / 2) - (elHeight / 2);
        $this.css({
          position: 'absolute',
          marginTop: '0',
          top: elTop
        });


      }
    });
  };

})(jQuery);


function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}


function set_dropdown(title){

  var title = $(title);

  title.show();
  title.append('<div class="shadow">&nbsp;</div>');

  var shadow = title.find('.shadow');
  shadow.css({background:"#000",opacity:0.45,position:'absolute',top:0,left:0});

  var menu = title.children('.drop-down-menu');
  menu.css("position","relative");
  menu.show();

  var mheight = menu.height();
  title.find('.drop-item').css({width:menu.width()+'px'});

  shadow.height(mheight+2);
  shadow.width(menu.width());

  shadow.hide();
  menu.hide();

  title.parent().hover(function(){
    var top  = title.height();
    var left = title.offset().left-$(this).parent('.horizontal-menu').offset().left;

    if($(this).parent('.horizontal-menu').css('position') == 'static')
      $(this).parent('.horizontal-menu').css('position','relative');

    $(this).addClass('hover');

    menu.css({
      position:'absolute',
      top:top+6,
      left:left-18,
      zIndex:1
    });

    shadow.css({
      position:'absolute',
      top:top+14,
      left:left-5,
      zIndex:0
    });
   
    var self = $(this).find('.drop-down-menu');

    self.stop();
    self.height(1);

    shadow.height(1);

    self.css({height:mheight});
    shadow.css({opacity:0.25,height:mheight+2});

    if(self.offset().left +
       self.width() > $(document).width()){
      self.css({
        left:$(this).offset().left-($(this).width()-10)
      });
    }
    self.show();
    shadow.show();

  }, function(){
    $(this).parent().andSelf().removeClass('hover');
    var self = $(this).find('.drop-down-menu,.shadow');
    self.stop();
    self.css({height:0});
    self.hide();
  });

  menu.children(".drop-item").hover(
    function(){
      $(this).addClass('hover');
    },
    function(){
      $(this).removeClass('hover');
    }
  );
}

function uiOSD(css){
  this.id = 'OSD_'+Math.floor(Math.random()*10000);
  this.bid = this.id+'background';
  $('body').append('<div class="uiOSD" id="'+this.id+'"></div>');
  $('body').append('<div class="uiOSDBackground" id="'+this.bid+'"></div>');
  this.window = $('#'+this.id);
  this.background = $('#'+this.bid);
  this.window.hide();
  this.background.hide();
  if(css){
    this.set_background_style(css);	
  }
  this.set_background_style = function(css){
    this.background.css(css);	
  }
  this.set_position = function(top,left){
    this.window.css({top:top,left:left});	
    this.background.css({top:top,left:left});
  }
  this.add = function(text){
    this.window.html(this.window.html()+text);
    this.background.width(this.window.width());
    this.background.height(this.window.height());
  }
  this.hide = function(){
    this.window.hide();
    this.background.hide();	
  }
  this.hide_all = function(){
    $('.uiOSD,.uiOSDBackground').hide();
  }
  this.show = function(text,timeout){
    $('.uiOSD,.uiOSDBackground').fadeOut(100);
    $('.uiOSDBackground').css('z-index','1000000000');
    $('.uiOSD').css('z-index','1000000001');
    this.window.html(text);
    if(any_ie()){
      this.window.show()
        this.background.show();
    }else{
      this.window.fadeIn(500);
      this.background.fadeIn(500);
    }
    this.background.width(this.window.width());
    this.background.height(this.window.height());
    osd_self = this;
    clearTimeout(this.timeTimeout);
    if(timeout)
      this.timeTimeout = setTimeout(function(){
        if(any_ie()){
          osd_self.background.hide();
          osd_self.window.hide();
        }else{
          osd_self.background.fadeOut(500);
          osd_self.window.fadeOut(500)
            }
      },timeout)
			
        if(ie_lesser()){
          offset_t = ($(document).scrollTop()+10);
          this.window.css({top:offset_t});
          this.background.css({top:offset_t});
        }
    return this;
  }
  return this;
}

function OverLight(){
  this.id = 'OverLight_'+Math.floor(Math.random()*10000);
  this.pid = 'OverLight_Panel'+Math.floor(Math.random()*10000);
  $('body').append('<div class="uiOverLight" id="'+this.id+'"><img class="OverLightLoader" src="/img/ui/loader-2.gif" />&nbsp;</div>');
  $('body').append('<div class="uiOverLightPanel" style="width:auto;" id="'+this.pid+'">&nbsp;</div>');

  this.window = $('#'+this.id);
  this.window.width($(document).width());
  if(ie_lesser()){
    this.window.height($(document).height());
    $('#OverLightLoader').css('top',$(document).scrollTop()*2)
      $('#OverLightLoader').css('left',$(document).scrollLeft()*2)
      }
  this.window.hide();
  this.panel = $('#'+this.pid);
  this.panel.hide();
  this.show = function(text){
    $('embed').hide();
		
    //$('object').hide();
    if(any_ie())
      this.window.show();
    else
      this.window.fadeIn(500);
    if(text){
      this.panel.html(text);
      var offset_l = this.panel.width()-(this.panel.width()*2);
      var offset_t = this.panel.height()-(this.panel.height()*2);
      this.panel.css({marginLeft:(offset_l/2)+'px',marginTop:(offset_t/2)+'px'});
      this.panel.fadeIn(500);
    }
		
    return this
  }
  this.obscure = function(){
    this.panel.css('margin-top','-12000px');	
  }
  this.set_width = function(width){
    this.panel.width(width);
    this.center();
  }
  this.set_text = function(text,title){
    if(!title)
      title = '';
    this.panel.html('<div class="panel-top" ><p>'+title+'</p><p class="close-btn"><a href="javascript:void(0);" class="panel-close"><img src="/img/ui/x.png" width="18" height="18" style="border:0" /></a></p></div><div class="panel-text">'+text+'</div>');
    panel_self = this;
    this.panel.find('.panel-close').unbind('click').click(function(){
      panel_self.hide();
    });
    this.panel.show();
    var offset_l = this.panel.width()-(this.panel.width()*2);
    var offset_t = (this.panel.height()-(this.panel.height()*2));
    if(ie_lesser())
      offset_t += ($(document).scrollTop()*2);
    this.panel.hide();
    this.panel.css({marginLeft:(offset_l/2)+'px',marginTop:(offset_t/2)+'px'});
    loadTransImgs();
    this.panel.fadeIn(500);
		
  }
  this.center = function(){
    var offset_l = this.panel.width()-(this.panel.width()*2);
    var offset_t = (this.panel.height()-(this.panel.height()*2));
    if(ie_lesser())
      offset_t += ($(document).scrollTop()*2);
    this.panel.hide();
    this.panel.css({marginLeft:(offset_l/2)+'px',marginTop:(offset_t/2)+'px'});	
    this.panel.show();
  }
  this.add_text = function(text){
    this.panel.html(this.panel.html()+text)	;
    var offset_l = this.panel.width()-(this.panel.width()*2);
    var offset_t = this.panel.height()-(this.panel.height()*2);
    this.panel.css({marginLeft:(offset_l/2)+'px',marginTop:(offset_t/2)+'px'});
  }
  this.hide = function(){
    if(any_ie())
      this.window.hide();
    else
      this.window.fadeOut(500);
				
    this.panel.fadeOut(500,function(){
      $('embed').show();
      //$('object').show();	
    });
		
    return this
  }
}



function ie_lesser(){
  if ( $.browser.msie && $.browser.version  <= 6)
    return true
    else
      return false
}
function any_ie(){
  if ( $.browser.msie )
    return true
    else
      return false
}


function init(){
  if($('#preview-splash'))
    runSplasher();
  adjustOverlay();
  $('.goto').click(function(){
    $.scrollTo($(this.rel),800);
    return false;
  });
  $('.cart-add-button').click(addToCart);
  $('.close-overlay-button').click(hideTopMessage);
  $('.close-overlay').click(hideTopMessage);
  preinit();
}
$(document).ready(function(){
  checkCartStatus();
});
function runSplasher(){
  var loaded_images = 0;
  var total_splash_images = $('#preview-splash .slide').length;
  $('#preview-splash .slide').hide();
  $('#preview-splash').append('<div class="splash-loader" style="width:673px;height:298px;border:solid 1px #ddd;text-align:center;"><img src="/img/ui/loader-2.gif" style="width:32px;height:32px;margin-top:134px;" /></div>');
  $('#preview-splash').show();
  $('#preview-splash .slide').each(function(){
    var img = new Image();
    $(img).load(function(){
      loaded_images += 1;
      if(total_splash_images == loaded_images){
        $('.splash-loader').fadeOut(1000,
                                    function(){
                                      $(this).remove();
                                      $('#preview-splash .slide:first').fadeIn(1000,function(){
                                        $('#preview-splash').cycle({
                                          fx:'fade',
                                          timeout:8000,
                                          after:fixSlideShow
                                        });
                                      });
                                    });
      }
    });
    var src = $(this).css('background-image').substring(4,$(this).css('background-image').length-1);
    if(src.match('"')){
      src = src.replace(/"/g,''); //"
                        }
        img.src = src;
    });
                                   }

    $(window).load(function(){
      initialOverlayHide();
      preinit();
    });

  function postAjax(){
    setUpHiddens();
    $('img').load(function()
    {
      $(this).css("width",$(this).width()+"px");
      $(this).css("height",$(this).height()+"px");
    });
    $('.cart-add-button').unbind('click').click(addToCart);
    $('.close-overlay-button').unbind('click').click(hideTopMessage);
    $('.close-overlay').unbind('click').click(hideTopMessage);

  }
  function setUpHiddens(){
    $('.show').unbind();
    $('.show-simple').unbind();
    $('.hidden').hide();
    $('.show').click(function(){
      $(this).hide(500);
      $($(this).attr('rel')).show(500);
      return false;
    });
    $('.show-simple').click(function(){
      $($(this).attr('rel')).show(500);
      return false;
    });
  }
  var ih = 0
    function initialOverlayHide(){
      if(ih == 0){
        hideOverlay();
        ih = 1;
      }
    }
  function showOverLoader(speed){
    if(!speed) speed = 500;
    $('.over-loader').fadeIn(speed);
  }
  function hideOverLoader(speed){
    if(!speed) speed = 500;
    $('.over-loader').fadeOut(speed);
  }

  function adjustOverlay(){
    $('.over-loader').vCenter();
    $('.overlay').css('width',$(window).width()+'px');
    $('.overlay').css('height',$(window).height()+'px');
  }
  function showOverlayButton(){
    $('.close-overlay-button').show();
  }
  function hideOverlayButton(){
    $('.close-overlay-button').hide();
  }
  function showTopMessage(text,title){
    overlay.show();
    if (text && title){
      overlay.set_text(text,title);
    }else if(text){
      overlay.set_text(text,"&nbsp;");
    }
  }
  function hideTopMessage(){
    $('.top-message').fadeOut(500,hideOverlay)
  }
  function hideOverlay(){
    ih = 1;
    $('.overlay').hide();
  }
  function showOverlay(callback){
    ih = 1;
    adjustOverlay();
    $('.overlay').show();
	
    if(callback){
      callback();
    }
  }
  function preinit(){
    var caps = $('.captionimg');
    for(c=0;c<caps.length;c++){
      $(caps[c]).find('img').load(function()
      {
        $(this.parentNode).css("width",$(this).width()+"px");
      }	);
    }
  }
  function setupWhatson(){
    $('#whatson').find('br').hide();
    $('#whatson').find('.whatsonnowdate:gt(0)').hide();
  }
  function repairMenu(){
    $('#navheader').children('li:first').html('<a href="/">Home</a>');
    $('#navheader').children().eq(1).html('<a href="/about/schedule">Schedule</a>');
    $('#navheader').children().eq(2).html('<a href="/about/programming">Programming</a>');
    $('#navheader').children().eq(3).html('<a href="/about/from_the_president">About WTCI</a>');
  }
  function throb(who){
    _throbOut(who);
  }
  function _throbIn(who){
    setTimeout(function(){
      $(who).fadeTo(400,1,function(){
        _throbOut(who)
      });
    },100);
  }
  function _throbOut(who){
    setTimeout(function(){
      $(who).fadeTo(400,.10,function(){
        _throbIn(who)
      });
    },500);
  }
  function setImageSizes(){
    $('img').each(function(){
      var check = $(this).attr('src').substring($(this).attr('src').lastIndexOf("."));
      if (check == ".png" || check == ".PNG"){
        if(!$(this).attr('width')){
          $(this).attr('width',$(this).width());
        }
        if(!$(this).attr('height')){
          $(this).attr('height',$(this).height());
        }
      }
    });
  }
  var _IE_WAIT = 0;
  function loadTransImgs(){
    if(typeof OpacityObjectImg == "function"){
      $('img').each(function(){
        _IE_WAIT += 20;
        $(this).load(function(){
          var self = this;
          setTimeout(function(){
            var check = $(self).attr('src').substring($(self).attr('src').lastIndexOf("."));
            if (check == ".png" || check == ".PNG"){
              objMyImage = new OpacityObjectImg(self);
              objMyImage.setBackground();
            }
          },_IE_WAIT);
        });
        $(this).attr('src',$(this).attr('src'));
      });
    }
  }
  function getRGB(color) {
    var result;

    // Check if we're already dealing with an array of colors
    if ( color && color.constructor == Array && color.length == 3 )
      return color;

    // Look for rgb(num,num,num)
    if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
      return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

    // Look for rgb(num%,num%,num%)
    if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
      return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

    // Look for #a0b1c2
    if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
      return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

    // Look for #fff
    if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
      return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

    // Otherwise, we're most likely dealing with a named color
    return colors[jQuery.trim(color).toLowerCase()];
  }
  function colorsToHex(col){
    var out = "";
    for (var c = 0; c<col.length;c++){
      out += col[c].toString(16);
      if(col[c].toString(16) == '0'){
        out += '0';
      }
    }
    if(col.length < 2){
      out += col[c].toString(16);
    }
    return out;
  }
  $(window).load(loadTransImgs);
  function is_set(what){
    return Boolean(typeof what != 'undefined' && what);
  }

  var searcho = new OverLight();
  function searchSub(){
    $('#search-form').attr('action', "/about/search/"+$(this).find('.search-term').val());
  }
  function getSearch(){
    searcho.set_text('<div  style="text-align:center"><h3>SEARCH WTCITV.ORG:</h3><form id="search-form" action="/about/search" method="post"><input style="width:350px;padding:4px;margin-left:-4px;" class="search-term" type="text" name="search_term" /><br/><br/><input type="submit" value="Search" /><br/><br/></form></div>',"Search");
    searcho.set_width(400);
    $('.search-term').focus();
    $('#search-form').submit(searchSub);
  }
  $(document).ready(function(){
    $('.search-link').click(function(){
      searcho.show();
      getSearch();
      return false;
    });
  });
