﻿var $j = jQuery;

if (false) { alert('OMFG!'); }

//in case we forget to get rid of console.log...
if (typeof console == 'undefined') {
  var console = { log: function () { } }
}

$j(document).ready(function () {

  $('.changefield').each(function () {
    var default_value = "";
    $(this).focus(function () {
      $(this).css('background-position', '0 -20px');
    });
    $(this).blur(function () {
      if (this.value == '') {
        $(this).css('background-position', '0 0px');
      }
    });
    $(this).change(function () {
      if (!this.value == '') {
        $(this).css('background-position', '0 -20px');
      }
    });
    if (this.value == '') {
      $(this).blur();
    }
  });
  $('.search').each(function () {
    $(this).focus(function () {
      $(this).css('background-position', '0 -23px');
    });
    $(this).blur(function () {
      if (this.value == '') {
        $(this).css('background-position', '0 0px');
      }
    });
    if (this.value == '') {
      $(this).blur();
    }
  });

  $j('#screenlock').css('opacity', '0.8')

  initializeHoverables();

});

jQuery.fn.closestPositioned = function () {
  var parent = $j(this).parent();
  if ($j(parent).is('body') || $j(parent).css('position') == 'absolute' || $j(parent).css('position') == 'relative') {
    return parent;
  }
  else {
    return $j(parent).closestPositioned();
  }
}

function ShowImage(el, cId) {
  $j('.hideableImage').hide();
  $j('#conceptImage' + cId).show();
  $j('#sortable').children().removeClass('selected');
  $j(el).parent().addClass('selected');
}

function Post(form) {
  form = $j(form);
  var url = form.attr('action');
  if (!url) { url = window.location.path; }
  //$j.post(form.attr('action'), form.serialize());
  $j.post(url, form.serialize());
}

function PostReview(form) {
  form = $j(form);
  var isBeingSaved = $j('#IsDraftSave').val();
  $j('#ReviewSubmitButton').hide();
  $j('#ReviewSaveButton').hide();
  $j('#ReviewCancelButton').hide();
  $j('#ReviewInProgress').show();
  $j.post('/utils/ajaxhandler.aspx', form.serialize(), function (data) {
    $j('#ReviewInProgress').hide();
    $j('#ReviewSubmitButton').show();
    $j('#ReviewSaveButton').show();
    $j('#ReviewCancelButton').show();
    if (isBeingSaved) {
      $j('#SaveSuccess').fadeIn('slow', function () { var t = setTimeout("$j('#SaveSuccess').fadeOut('slow')", 5000); });
    }
    $j('#IsDraftSave').val('0');
  });
}

function AddNotes(link) {
  $j('#IsDraftSave').val('1');
  $j('#NotesUrl').val(link.href);
  PostReview($j('#reviewForm'));
}


function PostComment(form) {
  form = $j(form);
  form.find('input[type="submit"]').hide();
  form.find('.comment-in-progress').show();
  $j.post('/utils/ajaxhandler.aspx', form.serialize(), function (data) {
    form.find('.comment-in-progress').hide();
    form.find('input[type="submit"]').show();
  });
}

function Invoke(action) {
  $j.post('/utils/ajaxhandler.aspx', { ActionType: action })
}

function InvokeConf(params, confirmation) {
  if (typeof confirmation === 'string') { if (!confirm(confirmation)) { return; } }
  $j.post(params.InvokeUrl ? params.InvokeUrl : window.location.path, params);
}

function SetupDefaultText() {
  var q = $j(this);
  var txt = q.attr('title');
  var onFocus = function () { if (q.val() == txt) { q.val('').removeClass('inactive'); } };
  var onBlur = function () { if (q.val() == '' || q.val() == txt) { q.val(txt).addClass('inactive'); } };
  q.focus(onFocus).blur(onBlur).parents('form').submit(onFocus);
  onBlur();
}

function formatCurrency(c) {
  return '$' + c.toFixed(2);
}

var permissionsToHide = new Array();

// Initializing popups appearing on hover (header)
function initializeHoverables() {

  $j('.hoverable').bind('mouseenter', function () {
    var elementIdToShow = $j(this).next('input[name="submenu-id"]').val();

    $j('#' + elementIdToShow).show();
    $j(this).addClass('hovered');
    permissionsToHide[elementIdToShow] = 0; // Not allowed to hide;
  }).bind('mouseleave', function () {
    var elementIdToHide = $j(this).next('input[name="submenu-id"]').val();

    permissionsToHide[elementIdToHide] = 1; // Allowed to hide;
    setTimeout(function () { hideHoverable(elementIdToHide) }, 100);
  });

  $j('.hoverable').each(function () {
    $j('#' + $j(this).next('input[name="submenu-id"]').val()).bind('mouseenter', function () {
      permissionsToHide[$j(this).attr('id')] = 0; // Not allowed to hide;
    }).bind('mouseleave', function () {
      var elementIdToHide = $j(this).attr('id');
      permissionsToHide[elementIdToHide] = 1; // Allowed to hide;
      setTimeout(function () { hideHoverable(elementIdToHide) }, 100);
    });
  });
}

function hideHoverable(hoverableId) {
  if (permissionsToHide[hoverableId]) {
    $j('#' + hoverableId).hide();
    $j('input[value="' + hoverableId + '"]').prev('a').removeClass('hovered');
  }
}

var Site = {
  windowContentSource: '',

  ShowMessage: function (container, message) {
    var el = $j('#' + container);
    if (el) {
      if ($j('#' + container + ':visible').length == 1) { el.fadeOut(200) };
      el.html(message).fadeIn(500);
      var y = Site.getScrollTop();
      if (y > 0) {
        var o = el.offset();
        var elY = o.top;
        window.scrollTo(0, elY - 50);
      }
    } else {
      alert(message.stripTags());
    }
  },

  ShowWinFromElement: function (title, cssSelector) {
    Site.ShowWin(title, $j(cssSelector).html());
    $j(cssSelector).html('');
    windowContentSource = cssSelector;
  },

  ShowWin: function (title, content) {
    $j('#win-title').html(title);
    $j('#win-content').html(content);
    Site.LockScreen();
    $j('#win').css({ top: $j(window).scrollTop() }).show();
  },

  CloseWin: function () {
    $j('#win').hide();
    Site.UnLockScreen();
    $j('#win-title').html('');
    if (windowContentSource.length > 0) {
      $j(windowContentSource).html($j('#win-content').html());
      windowContentSource = '';
    }
    $j('#win-content').html('');
  },

  LockScreen: function () {
    $j('#screenlock').show();
  },

  UnLockScreen: function () {
    $j('#screenlock').hide();
  },

  getScrollTop: function () {
    if (self.pageYOffset) {
      // all except Explorer
      return self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
      // Explorer 6 Strict
      return document.documentElement.scrollTop;
    } else if (document.body) {
      // all other Explorers
      return document.body.scrollTop;
    }
  },

  refreshLightbox: function () {
    $j('.lightboxed,.fancyboxed').fancybox({ autoScale: false });
  }
}

function loadExternalFile(fileName) {
  var fileType = getFileExtension(fileName);
  var fileRef;

  if (fileType == 'js') { //if filename is a external JavaScript file
    fileRef = document.createElement('script');
    fileRef.setAttribute('type', 'text/javascript');
    fileRef.setAttribute('src', fileName);
  }
  else if (fileType == 'css') { //if filename is an external CSS file
    fileRef = document.createElement('link');
    fileRef.setAttribute('rel', 'Stylesheet');
    fileRef.setAttribute('type', 'text/css');
    fileRef.setAttribute('href', fileName);
  }
  else {
    throw 'Trying to load a file of an unsupported type';
  }

  if (typeof fileRef != 'undefined') {
    document.getElementsByTagName('head')[0].appendChild(fileRef);
  }
}

function getFileExtension(fileName) {
  return fileName.split('.').pop();
}

String.prototype.trim = function () {
  return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function randomString(string_length) {
  var randomstring = '';

  for (var i = 0; i < string_length; i++) {
    randomstring += Math.floor(Math.random() * 10); ;
  }

  return randomstring;
}

var review = {
  editReview: function (reviewId) {
    $j('#review-' + reviewId + '-body').hide();
    $j('#review-' + reviewId + '-edit-form').show();
  },

  cancelReviewEdit: function (reviewId) {
    var parentForm = $j('#review-' + reviewId + '-edit-form');

    $j(parentForm).find('input, textarea').each(function () {
      var originalValueInput = $j(this).next('input.original-value');
      if (this.tagName.toUpperCase() == 'input') {
        $j(this).val($j(originalValueInput).val());
      }
      else {
        $j(this).html($j(originalValueInput).val());
      }
    });

    $j(parentForm).hide();
    $j('#review-' + reviewId + '-body').show();
  },

  saveReview: function (sender, reviewId) {
    var form = $j(sender);

    Post(sender);

    $j(form).hide();
    $j('#review-' + reviewId + '-body').show();
  }
}
