$(document).ready(function(){
  vocabViewComments='<a href="#" onclick="return false">Comments</a>';
  vocabViewText='<a href="#" onclick="return false">View Text</a>';
  vocabProdRemove='Remove from basket';
  vocabSiteTagsView='view all site tags';
  vocabSiteTagsHide='hide all site tags';
/* Setup channel number button scroller */
  $(".dbChannelNum > a").click(function() {
    myParameters=this.href;
    myParameters='/ajax-df-vidlist.php' + myParameters.substring(myParameters.indexOf('?'));
    myTarget = $(this).parent().parent().siblings(".dbVidCtnr");
    newHighlight=$(this).parent();

    if ((newHighlight.prev().html()=='...')||(newHighlight.next().html()=='...')) { return true; };

    $.get(myParameters, function(data){
      myTarget.html(data);
      newHighlight.siblings().removeClass("dbChannelCurrent");
      newHighlight.addClass("dbChannelCurrent");
    });
        
    return false;
  });
/* Channel expander */
  addLinksForChannelExpander();
  setupWideChannelNumberClicker();
/* Video comment functions */
  vcVidValue=window.vcVidValue||'empty';
  vcShowBoth=window.vcShowBoth||false; // vcShowBoth = true means that the comments should be shown under the video text
  if (vcVidValue!=='empty') {
    if (vcShowBoth) {
      $(".mainPageText").after('<div id="vcCommentContainerOut"><div id="vcCommentContainerIn"><div id="vcCommentContainer"></div></div></div>');
      showCommentsAsWellAsVideoText();
    } else {
      $("#vidViewChanger").html(vocabViewComments);
      $("#vidViewChanger").click(function() { return switchToComments(); });
      vcOriginalVideoText='';
    }
  }
/* End video comment functions */
/* Product functions */
  doAjaxProducts=window.doAjaxProducts||false;
  aPzb=window.aPzb||false;
  if (doAjaxProducts && aPzb) {
    aPzu=window.aPzu||'';
//    $(".pQty").css('border','2px blue solid');
    removeBasicClickFromProductButtons();
    addAjaxToQtyFields();
  }
  addProductVideoLinks();
  if (!$("#basketCtnr").html()) $("#basketCtnr").css('display', 'none'); // Fixes problem with IE6 / IE7 layouts pushing down left column.
  if (!$("#mainCtnr").html()) $("#mainCtnr").css('display', 'none'); // Fixes problem with IE6 / IE7 layouts pushing down left column.
/* End product functions */
/* Add tag cloud displayer */
  if ($('#siteTagCloud') && $('.vTagListCtnr') && !$('.vTagListCtnr #viewCloud').size()) {
    if ($('#siteTagCloud').css('display') === 'none') {
      $('.vTagListCtnr:not(#siteTagCloud) .tag-list').append('<li id="viewCloud" class="vtag"><a id="siteTagCloudToggle" onclick="siteTagCloudToggle();">'+vocabSiteTagsView+'</a></li>');
    }
  }
/* End tag cloud displayer */
  changeColHeights();
});

function addLinksForChannelExpander () {
  $.each($("#detailBody .dfChannelLink:not(.noMore)"), function() {
    capLinkto = convertHrefToChannel($(this).attr('href'));
    if (capLinkto!=='') {
      $(this).before('<div class="channelExpander"><a href="#'+capLinkto+'"><img src="/images/style/dbc-more.png"></a></div>');
    }
  });
  $(".channelExpander > a").click(function(){ return showChannelWide($(this)); });
}
function addLinksForChannelShrinker() {
  $.each($("#detailBodyWide:not(.dbwFixed) .dfChannelLink"), function() {
    capLinkto = convertHrefToChannel($(this).attr('href'));
    if (capLinkto!=='') {
      $(this).parent().prepend('<div class="channelExpander"><a href="#'+capLinkto+'"><img src="/images/style/dbc-less.png"></a></div>');
    }
  });
  $("#detailBodyWide .channelExpander > a").unbind().click(function(){ return showChannelNarrow(); });
}
function showChannelNarrow() {
  $('#mainCtnr').css('left','-174px');
  $('#videoThumbLinksCtnr').css('left','825px');
  $("#detailBody").css('display','block');
  if ($.browser.msie && ($.browser.version < 7)) $("#mainCtnr").css('display','block');
  $("#detailBodyWide").css('display','none');
  $("#sponsors").removeClass("sponsorsWide");
  return false;
}
function showChannelWide(capParent) {
  capLinkto = convertHrefToChannel(capParent.attr('href'));
  previousTitle = capParent.parent().siblings('.dfChannelLink').html();
  previousTitle = ' \
<div class="dbChannelHead"></div><div class="dbChannel"> \
<div class="dbChannelTitleCtnr"><div class="dbChannelTitleTop"></div> \
<h2 class="dbChannelTitle"> \
<a class="dfChannelLink" href="#">' + previousTitle + '</a></h2> \
<div class="dbChannelTitleBase"></div></div> \
</div><div class="dbChannelFoot"></div> \
<div class="dbVidCtnr"><p style="margin-left: 4px">Loading channel...</p></div> \
  ';
  $('#detailBodyWide').html(previousTitle);
  $('#mainCtnr').css('left','-2174px');
  $('#videoThumbLinksCtnr').css('left','-825px');
  $("#detailBody").css('display','none');
  if ($.browser.msie && ($.browser.version < 7)) $("#mainCtnr").css('display','none');
//  $("#detailBodyWide").css('display','block');
  $("#detailBodyWide").slideDown('slow');
  $("#sponsors").addClass("sponsorsWide");
  $.ajax({
    type: "GET",
    url: "/ajax-wide-channel.php",
    data: "channel="+capLinkto,
    success: function(data){
      if (typeof(stcMessage)!='undefined') stcMessage='<div class="vcMessage">'+stcMessage+'</div>';
      else stcMessage='';
      $("#detailBodyWide").html(stcMessage+data);
      addLinksForChannelShrinker();
      setupWideChannelNumberClicker();
    },
    error: function() {
      alert('Sorry, that channel\'s contents could not be loaded at this time.');
      addLinksForChannelShrinker();
    }
  });
  return false;
}
function setupWideChannelNumberClicker() {
  $("#detailBodyWide .dbChannelNum > a").unbind().click(function() {
    myParameters = $(this).attr('href');
    if (myParameters.substring(0,7)==='http://') {
      myParameters = myParameters.substring(8);
      myParameters = myParameters.substring(myParameters.indexOf('/'));
    }
    if (typeof(capLinkto) == 'undefined') {
      capLinkto = myParameters.substring(1,myParameters.indexOf('?'));
    }
    myParameters = '/ajax-wide-channel.php' + myParameters.substring(myParameters.indexOf('?')) + "&channel="+capLinkto;
    myTarget = $("#detailBodyWide");
    newHighlight = $(this).parent();

    if ((newHighlight.prev().html()=='...')||(newHighlight.next().html()=='...')) { return true; };

    $.get(myParameters, function(data){
      myTarget.html(data);
      newHighlight.siblings().removeClass("dbChannelCurrent");
      newHighlight.addClass("dbChannelCurrent");
      addLinksForChannelShrinker();
      setupWideChannelNumberClicker();
    });
    
    return false;
  });
}

function showCommentsAsWellAsVideoText(stcMessage) {
  $("#vcCommentContainer").html('Loading comments...');
  $.ajax({
    type: "GET",
    url: "/ajax-getcomments.php",
    data: "vid="+vcVidValue,
    success: function(data){
      if (typeof(stcMessage)!='undefined') stcMessage='<div class="vcMessage">'+stcMessage+'</div>';
      else stcMessage='';
      vCCTitle = '<h2>Comments</h2>';
      $("#vcCommentContainer").html(vCCTitle+stcMessage+data);
      $("form#vcAddCommentForm").bind("submit", function(e) {
        postComment2($("#vcAddCommentForm").val());
        return false;
      });
    },
    error: function() { alert('Sorry, the comments could not be loaded at this time.'); }
  });
}
function switchToComments(stcMessage) {
  if ($("#vidViewChanger").html()===vocabViewComments) vcOriginalVideoText=$("#mainPageTextIn").html();
  $("#mainPageTextIn").html('<div id="vcCommentContainer">Loading comments...</div>');
  $.ajax({
    type: "GET",
    url: "/ajax-getcomments.php",
    data: "vid="+vcVidValue,
    success: function(data){
      if (typeof(stcMessage)!='undefined') stcMessage='<div class="vcMessage">'+stcMessage+'</div>';
      else stcMessage='';
      $("#vcCommentContainer").html(stcMessage+data);
      $("form#vcAddCommentForm").bind("submit", function(e) {
        postComment($("#vcAddCommentForm").val());
        return false;
      });
    },
    error: function() { alert('Sorry, the comments could not be loaded at this time.'); }
  });
  $("#vidViewChanger").html(vocabViewText);
  $("#vidViewChanger").unbind().click(function() { switchToText(); });
}
function switchToText() {
  if (vcOriginalVideoText=='') { //didn't save the text correctly, so try and get it now
    $.ajax({
      type: "GET",
      url: "/ajax-getVideoText.php",
      data: {
        vid:  vcVidValue
      },
      async: true,
      cache: true,
      success: function(ajaxVideoText) { vcOriginalVideoText=ajaxVideoText; }
    });
  }
  $("#mainPageTextIn").html(vcOriginalVideoText);
  $("#vidViewChanger").html(vocabViewComments);
  $("#vidViewChanger").unbind().click(function() { switchToComments(); });
}
function postComment(pcFormId) {
  $.ajax({
    type: "POST",
    url: "/ajax-postComment.php",
    data: {
      vid:  $("#vcInputVid").val(),
      code: $("#vcInputCode").val(),
      commentText: $("#vcInputText").val()
    },
    cache: false,
    success: function(msg) { switchToComments(msg); },
    error: function() { alert('Sorry, the comment was not posted. Please reload the page and try again.'); }
  });
}
function postComment2(pcFormId) {
  $.ajax({
    type: "POST",
    url: "/ajax-postComment.php",
    data: {
      vid:  $("#vcInputVid").val(),
      code: $("#vcInputCode").val(),
      commentText: $("#vcInputText").val()
    },
    cache: false,
    success: function(msg) { showCommentsAsWellAsVideoText(msg); },
    error: function() { alert('Sorry, the comment was not posted. Please reload the page and try again.'); }
  });
}

function removeBasicClickFromProductButtons() {
  $(".pBtn").unbind().click(function(){
    if ($(this).val()===vocabProdRemove) {
       $ajaxData="action=add"+
               "&zu="+aPzu+
               "&zb="+aPzb+
               "&pr="+$(this).parent().parent().parent().parent().children('.pId').val()+
               "&qty=0"+
               "&co=123"; // ~~~ Code should be a hash of the userid or something similar ~~~
      $selfReference=$(this).parent().parent();
      $limit=$(this).parent().parent().parent().parent().children('.pLim').val()
      $selfReference.html('<div class="pBoxes">Removing...</div>');
      $.ajax({
        type: "GET",
        url: "/ajax-basket.php",
        data: $ajaxData,
        success: function(data){
          $("#basketCtnr").css('display','block');
          $("#basketCtnr").html(data);
          $selfReference.load('/ajax-product-inputs.php?lim='+$limit+'&qty=0', null, function() {
            removeBasicClickFromProductButtons();
            addAjaxToQtyFields();
          });
        },
        error: function() { alert('Sorry, there was a problem processing your order.'); }
      });     
    } else {
      alert("Please choose a quantity to add to your basket.");
      return false;
    }
  });
}
function addAjaxToQtyFields() {
  $(".pQty").unbind().change(function(){
    if (!isNaN(Number($(this).val()))) {
      qtyRequested = $(this).val();
      $ajaxData=
        "action=add"+
        "&zu="+aPzu+
        "&zb="+aPzb+
        "&pr="+$(this).parent().parent().parent().parent().parent().children('.pId').val()+
        "&qty="+qtyRequested+
        "&co=123";
      $selfReference=$(this).parent().parent().parent();
      $selfReference.html('<div class="pBoxes">Updating...</div>');
      $.ajax({
        type: "GET",
        url: "/ajax-basket.php",
        data: $ajaxData,
        success: function(data){
          $("#basketCtnr").css('display','block');
          $("#basketCtnr").html(data);
          $selfReference.html(''+
            '<div class="pBoxes pbQty"><input type="hidden" name="qty" value="0" />&nbsp;</div>'+
            '<div class="pBoxes pbSubmit"><input class="pBtn" type="image" src="/images/style/button_update_basket.png" alt="'+vocabProdRemove+'" value="'+vocabProdRemove+'" /></div>'+
            '<div class="pBoxes pbCurrent">You have '+qtyRequested+' in your basket</div>');
          removeBasicClickFromProductButtons();
        },
        error: function() { alert('Sorry, there was a problem processing your order.'); }
      });
    }
  });
}
function addProductVideoLinks() {
  $(".dvbpText").each(function () {
    hasLink = $(this).children('h3').children('a').attr('href');
    if (hasLink !== undefined) {
      if ($(this).next('.pBoxCtnr').children('.pBoxInputs').children().hasClass('pbQty')
        && !$(this).next('.pBoxCtnr').children('.pBoxInputs').children().hasClass('pbVideoLink')
      ) {
        $(this).next('.pBoxCtnr').children('.pBoxInputs').children('.pbSubmit').after('<div class="pBoxes pbVideoLink"><a href="'+hasLink+'">View video</a></div>');
      } else {
        // do nothing
      }
    }
  });
}

function siteTagCloudToggle() {
  $('#siteTagCloud').toggle();
  if ($('#siteTagCloud').css('display') === 'none') viewCloudText = vocabSiteTagsView;
  else viewCloudText = vocabSiteTagsHide;
    $('#viewCloud').html('<li id="viewCloud" class="vtag"><a id="siteTagCloudToggle" onclick="siteTagCloudToggle();">'+viewCloudText+'</a></li>');
}

function changeColHeights() {
  minContentColumnHeight = 640;
  maxContentColumnHeight = 1500;

  headerHeight = $('#headerCtnr').height();
  heightCol1 = getHeightOf("#menuCtnr");
  heightCol2Thumbs = getHeightOf("#detailBodyRuler");
  heightCol2Sponsors = getHeightOf("#sponsors");
  heightCol2 = heightCol2Thumbs + heightCol2Sponsors;
  heightCol3Video = Math.max(getHeightOf("#mainvideo"), getHeightOf("#imageInsteadCtnr"));
  heightCol3Buttons = getHeightOf("#sidemenuOut");
  heightCol3Text = getHeightOf(".mainPageText");
  heightCol3 = heightCol3Video + heightCol3Buttons + heightCol3Text;
  heightCol4 = getHeightOf("#vtlRuler");
  heightCol5 = getHeightOf("#s2Ctnr") - headerHeight; // + 43; // +43 is a hack since IE is reporting different height to FF
  tallestNonMainColumn = Math.max(heightCol1, Math.max(heightCol4, heightCol5));
  maxContentColumnHeight = Math.max(maxContentColumnHeight, heightCol1); // if C1 is very tall, use this as the yardstick
  
  if ((tallestNonMainColumn > minContentColumnHeight)) {
    newHeight = Math.min(tallestNonMainColumn, maxContentColumnHeight);
    $("#menuCtnr").height(newHeight);
    $("#detailBody").height(newHeight - heightCol2Sponsors);
    if ($("#detailBody").hasClass('dbNoSponsors')) $("#detailBody").removeClass('dbNoSponsors');
    mainPageTextHeight = newHeight - heightCol3Video - heightCol3Buttons;
    if (vcShowBoth) {
      mainPageTextHeight = mainPageTextHeight - 208;
      mainPageTextHeight = Math.min(mainPageTextHeight, $('#mainPageTextIn').height() + 30); // If the video text is short, collapse the text box so the video comments appear higher on the page
    }
    $(".mainPageText").height(mainPageTextHeight);
    $("#videoThumbLinksCtnr").height(newHeight);
    $("#s2Ctnr").height(newHeight + headerHeight);
  }

  if ($("#bookme-text").html() || $("#bookme-msg").html()) {
    $innerHeight = $('#bookme-text').height() + $('#bookme-form').height() + $('#bookme-msg').height();
    $('.mainPageText').css('height', $innerHeight+30+'px');
  }

}
function getHeightOf(myJquerySearchString) {
  myJqueryElement = $(myJquerySearchString);
  if (myJqueryElement.size() && (myJqueryElement.css('display') !== 'none')) {
    return myJqueryElement.height();
  } else {
    return 0;
  }
}
function convertHrefToChannel(inputHref) {
  if (inputHref.substring(0,7)==='http://') {
    channelName = inputHref.substring(8);
    channelName = channelName.substring(channelName.indexOf('/') + 1);
    channelName = channelName.substring(channelName.indexOf('#') + 1);
  } else {
    channelName = inputHref.substring(1);
  }
  return channelName;
}