//disable console logging
//console.log = function() {}

$.ajaxSetup({
    type: "POST",
    url: "/proxy/"
});

function displayDialog(dialogId) {
  $(dialogId).dialog({
    modal: true,
    resizable: true
  });
}

function slugify(text) {
	text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
	text = text.replace(/-/gi, "_");
	text = text.replace(/\s/gi, "-");
	return text;
}

function typeOf(value) {
  var s = typeof value;
  if (s === 'object') {
    if (value) {
      if (value instanceof Array) {
          s = 'array';
      }
    } else {
      s = 'null';
    }
  }
  return s;
}

function requestSuccessHandler(data) {
  if (data.head.messages.length > 0) {
    $('#messageBox').removeClass('ui-state-error').addClass('ui-state-success').html('<span class="ui-icon ui-icon-circle-check"></span> ' + data.head.messages[0][1]).show().delay(8000).fadeOut(1000);
  } else if (data.head.status == 200) {
    $('#messageBox').removeClass('ui-state-error').addClass('ui-state-success').html('<span class="ui-icon ui-icon-circle-check"></span> Action Executed Successfully').show().delay(8000).fadeOut(1000);
  }
}

function requestErrorHandler(xhr,dialogId) {//dialogId should already have the # if coming from a dialog
  var $messageBox = (undefined != dialogId ? $(dialogId+'Notes') : $('#messageBox'))
  var errorMessages = JSON.parse(xhr.responseText).head.errors;
  for (var x = 0, y = errorMessages.length; x < y; x ++){
    if (errorMessages[x][0] == null) {
      $messageBox.removeClass('ui-state-success').addClass('ui-state-error').html('<span class="ui-icon ui-icon-alert"></span> ' + errorMessages[1][1]).show();
    } else {
      $(dialogId + '_' + errorMessages[x][0] + 'Status').text(errorMessages[x][1]).parent().parent().addClass('ui-state-error ui-corner-all');
    }
  }
  if (undefined == dialogId) {
    $messageBox.delay(8000).fadeOut(1000);
  }
}

function showObjectDetailsDialog(objectType, objectId) {
  var $dialog = $('<div></div>');
  var dialogId = 'details' + objectId;
  $dialog.attr('id',dialogId);
  $dialog.dialog({
    modal: true,
    resizable: true,
    dialogClass: 'dlg',
    width: 800,
    height: 600,
    title: 'Details',
    close: function() { 
      $(this).remove(); 
    },
    buttons: {
      "Close" : function() {
        $(this).remove();
      }
    }
  });
  getObjectDetailsModule(objectType, objectId, dialogId);
}

function getObjectDetailsModule(object,objectId,targetId) {
  if (targetId === undefined) {
    targetId = 'details' + objectId;
  }
  $('#' + targetId).each(function(){
    $(this).removeClass('ui-state-error').html($('#loading').html());
    $(this.childNodes[0]).prepend('<h1>loading ' + object + ' module...</h1>');
    $(this).load('/control-panel/objectDetailsModule.html?obj=' + object + '&objId=' + objectId, function(response, status, xhr){
        if (status == 'error') {
          $(this).html(xhr.status + " " + xhr.statusText).addClass('ui-widget ui-state-error ui-corner-all');
        } else {
          $('#showModule' + objectId).each(function(){$(this).hide()});
          $('#hideModule' + objectId).each(function(){$(this).show()});
        }
    });
  });
}

function getObjectListModuleByCriteria(targetId,object,criteria,start,limit,callback) {
  $('#' + targetId).removeClass('ui-state-error').html($('#loading').html());
  $('#' + targetId + ' > div').prepend('<h1>loading ' + object + ' list module...</h1>');
//this line was breaking the control panel on app create, why was i sending it the callback?
//  $('#' + targetId).load('/control-panel/objectListModule.html?targetId=' + targetId + '&obj=' + object + '&criteria=' + encodeURIComponent(JSON.stringify(criteria)) + '&start=' + start + '&limit=' + limit + '&callback=' + (undefined != callback ? callback : ''), function(response, status, xhr){
  $('#' + targetId).load('/control-panel/objectListModule.html?targetId=' + targetId + '&obj=' + object + '&criteria=' + encodeURIComponent(JSON.stringify(criteria)) + '&start=' + start + '&limit=' + limit, function(response, status, xhr){
      if (status == 'error') {
        $('#' + targetId).html($('#respError').html());
      } else {
        eval(callback);
      }
  });
}

function getObjectListModuleById(targetId,object,id,start,limit,callback) {
  $('#' + targetId).removeClass('ui-state-error').html($('#loading').html());
  $('#' + targetId + ' > div').prepend('<h1>loading ' + object + ' list module...</h1>');
  $('#' + targetId).load('/control-panel/objectListModule.html?targetId=' + targetId + '&obj=' + object + '&objId=' + id + '&start=' + start + '&limit=' + limit + '&callback=' + (undefined != callback ? callback : ''), function(response, status, xhr){
      if (status == 'error') {
        $('#' + targetId).html($('#respError').html());
      } else {
        eval(callback);
      }
  });
}

function getObjectListModuleByIdList(targetId,object,objIds,start,limit,callback) {
  $('#' + targetId).removeClass('ui-state-error').html($('#loading').html());
  $('#' + targetId + ' > div').prepend('<h1>loading ' + object + ' list module...</h1>');
  $('#' + targetId).load('/control-panel/objectListModule.html?targetId=' + targetId + '&obj=' + object + '&objIds=' + objIds + '&start=' + start + '&limit=' + limit + '&callback=' + (undefined != callback ? callback : ''), function(response, status, xhr){
      if (status == 'error') {
        $('#' + targetId).html($('#respError').html());
      } else {
        eval(callback);
      }
  });
}

function getObjectListModuleByQuery(targetId,object,query,start,limit,callback) {
  $('#' + targetId).removeClass('ui-state-error').html($('#loading').html());
  $('#' + targetId + ' > div').prepend('<h1>loading ' + object + ' list module...</h1>');
  $('#' + targetId).load('/control-panel/objectListModule.html?targetId=' + targetId + '&obj=' + object + '&query=' + encodeURIComponent(query) + '&start=' + start + '&limit=' + limit + '&callback=' + (undefined != callback ? callback : ''), function(response, status, xhr){
      if (status == 'error') {
        $('#' + targetId).html($('#respError').html());
      } else {
        eval(callback);
      }
  });
}


////////////////////////////
// TASKS
////////////////////////////
  
function loadThread(flowId, dropId, commentId){
  var postData = {
    "url" : "/drop/" + flowId + "/" + dropId + "/comment?threadId=" + commentId + "&hints=0",
    "method" : "GET",
    "ctype" : "json"
  };
  $.ajax({
    data: postData,
    success: function(data){
      renderComments(data.body[0]['children'],flowId,dropId,commentId);
    },
    error: function(xhr){
      requestErrorHandler(xhr, dialogId);
    }
  });
}

function renderComments(comments,flowId,dropId,commentId){
  var $target = $('#comments' + commentId);
  $target.empty();
  for (var x=0, y=comments.length; x < y; x++) {
    var $commentItem = $('<li></li>').attr('id','comment'+comments[x]['id']);
    var $commentCite = $('<cite></cite>');
    var $commentCreator = $('<a onclick="showObjectDetailsDialog(\'identity\',\'' + comments[x].creatorId + '\');">' + comments[x].creator.fname + ' ' + comments[x].creator.lname + ' (' + comments[x].creator.alias +')</a>');
    var createdDate = new Date(comments[x].creationDate);
    var lastEditDate = new Date(comments[x].lastEditDate);
    var $commentDate = ' | ' + createdDate.toUTCString() + (comments[x].creationDate != comments[x].lastEditDate ? ' (Edited on ' + lastEditDate.toUTCString() + ') ' : ' ');
    var $commentReplyLink = $('<a title="reply to this comment" onclick="forumAddDropComment(\'' + flowId + '\',\'' + dropId + '\',\'' + comments[x].id + '\');">Reply</a>');
    var $commentText = $('<span>' + comments[x].text + '</span>');
    $commentCite.append($commentCreator);
    $commentCite.append($commentDate);
    $commentCite.append($commentReplyLink);
    $commentItem.append($commentCite);
    $commentItem.append($commentText);
    $target.append($commentItem);
    
    if (comments[x].hasChildren) {
      var $sublist = $('<ul></ul>').attr('id','comments' + comments[x].id);
      $target.append($sublist);
      renderComments(comments[x].children,flowId,dropId,comments[x].id);
    }
  }
}
  
  
function loadForum(node,path,filter,start) {
  var url = '/forum/forumFlowTemplate.html?flowPath=' + path + '&node=' + node;
  if (undefined != filter && filter != '') {
    url += '&filter=' + filter;
  }
  if (undefined != start) {
    url += '&start=' + start;
  }
  if (node.indexOf('#') < 0) { node = '#' + node };
  $(node).load(url);
}


function forumAddDrop(flowPath, flowId, category) {
  var dialogId = '#forumAddDropDlg';
  $('#dropTitle').val('');
  $('#dropDescription').val('');
  
  $(dialogId).dialog({
    modal: true,
    resizable: true,
    dialogClass: 'dlg',
    width: 800,
    height: 400,
    buttons: [
      { 
        text: "Submit",
        priority: "primary",
        classes: "ui-priority-primary",
        click: function() {
          var formData = JSON.stringify({
            "path" : {
              "type" : "path",
              "value" : flowPath
            },
            "elems" : {
              "title" : { "type" : "string", "value" : $('#dropTitle').val() },
              "description" : { "type" : "string", "value" : $('#dropDescription').val() },
              "sourcename" : {"type" : "string", "value" : document.title },
              "sourceurl" : { "type" : "url", "value" : window.location.href },
              "category": category,
              "droptype": $('#dropType option:selected').val()
            }
          });
          var postData = {
            "url" : "/drop",
            "method" : "POST",
            "data" : formData,
            "ctype" : "json"
          };
          $.ajax({
            data: postData,
            success: function(data){
              $('#forumNode').load('/forum/forumFlowTemplate.html?flowPath=' + flowPath + (category != '' ? '&filter=' + category : ''), function(){});
              requestSuccessHandler(data);
              $(dialogId).dialog("close");
            },
            error: function(xhr){
              requestErrorHandler(xhr, dialogId);
            }
          });
        }
      },
      {
        text: "Cancel",
        priority: "secondary",
        classes: "ui-priority-secondary",
        click: function() { $(dialogId).dialog("close") }
      }
    ]
  });
}

function forumAddDropComment(flowId, dropId, commentId) {
  var dialogId = '#forumAddDropCommentDlg';
  var url;
  $('#dropComment').val('');
  displayDialog(dialogId);
  $(dialogId).dialog( "option", "buttons", [
    { 
      text: "Submit",
      priority: "primary",
      classes: "ui-priority-primary",
      click: function() {
        var formData = {};
        if (undefined != flowId) {
          url = '/flow/' + flowId + '/comment';
        }
        if (dropId != undefined) {
          url = '/drop/' + flowId + '/' + dropId + '/comment';
        }
        formData['text'] = {
            "type" : "string",
            "value" : $('#dropComment').val()
          }
        if (undefined != commentId) {
          formData['parentId'] = {
            "type" : "id",
            "value" : commentId
          }
        }  
        formData = JSON.stringify(formData);
        var postData = {
          "url" : url,
          "method" : "POST",
          "data" : formData,
          "ctype" : "json"
        };
        $.ajax({
          data: postData,
          success: function(data){
            if (undefined != commentId) {
              loadThread(flowId,dropId,data.body.topParentId.value);
            } else {
              $('#threads' + dropId + 'tree').load('/forum/forumFlowTemplate.html?flowId=' + flowId + '&dropId=' + dropId + ' #thread' + dropId, function(){
                  $('#thread' + dropId).show();
              });
            }
            $('#forumAddDropCommentDlg').dialog("close");
            requestSuccessHandler(data);
          },
          error: function(xhr){
            requestErrorHandler(xhr, dialogId);
          }
        });
      }
    },
    {
      text: "Cancel",
      priority: "secondary",
      classes: "ui-priority-secondary",
      click: function() { $(dialogId).dialog("close") }
    }
  ]);
}

function forumDeleteComment(flowId, dropId, commentId){
  var dialogId = '#forumDeleteCommentDlg';
  displayDialog(dialogId);
  $(dialogId).dialog( "option", "buttons", [
    { 
      text: "Delete Comment",
      priority: "primary",
      classes: "ui-priority-primary",
      click: function() {
        
        if (undefined != flowId) {
          url = '/flow/' + flowId + '/comment/' + commentId;
        }
        if (dropId != undefined) {
          url = '/drop/' + flowId + '/' + dropId + '/comment/' + commentId;
        }
        var postData = {
          "url" : url,
          "method" : "DELETE",
          "ctype" : "json"
        };
        $.ajax({
          data: postData,
          success: function(data){
            $(dialogId).dialog("close");
            $('#comments' + dropId).load('/forum/forumCommentsTemplate.html?flowId=' + flowId + '&dropId=' + dropId, function(){});
            requestSuccessHandler(data);
          },
          error: function(xhr){
            requestErrorHandler(xhr, dialogId);
          }
        });
      }
    },
    {
      text: "Cancel",
      priority: "secondary",
      classes: "ui-priority-secondary",
      click: function() { $(dialogId).dialog("close") }
    }
  ]);
}


////////////////////////////
// PERMISSIONS
////////////////////////////


function loadPermissionsObject(tabTarget,obj,objId,member) {
  $('#' + tabTarget + objId + ' #' + member + objId).empty().html($('#loading').html());
  $('#' + tabTarget + objId + ' #' + member + objId + ' > div').prepend('<h1>loading ' + obj + ' ' + member + ' module...</h1>');
  $('#' + tabTarget + objId + ' #' + member + objId).load('/control-panel/permissionsModule.html?obj=' + obj + '&objId=' + objId + '&member=' + member + '&tabTarget=' + tabTarget);
}

function prependIdentitySelectors(resultsListId,member,objectId) {
  //callback function to add selection to the list
  var resultsList = $('#' + resultsListId);
  resultsList.children().each(function(){
    if ($(this).hasClass('empty') != true) {
      var tmpl = '';
      tmpl += '<div class="ui-button ui-state-default ui-corner-all" title="Select this identity to add permissions" ';
      tmpl += 'onclick="addIdentityToPermissionsEdit(this.parentNode,\'' + objectId + '\',\'' + member + '\')">';
      tmpl += '<span class="ui-icon ui-icon-circle-plus"></span>';
      tmpl += '</div>';
      $(this).prepend(tmpl); 
    }
  });
}

function addIdentityToPermissionsEdit(identity,objectId,member) {
  $(identity).addClass('ui-state-highlight');
  $idsToAdd = $('#' + objectId + member + 'IdentitiesToAdd');
  var arr = ($idsToAdd.val() == '' ? new Array() : new Array($idsToAdd.val()));
  arr.push(identity.id);
  $idsToAdd.val(arr);
}
function submitPermissionAccessToggle(tabTarget,type,access,obj,objId,member) {
  var postData = {
    "url" : "/" + obj + "/" + objId + "/" + member + "?hints=0",
    "method" : "GET",
    "ctype" : "json"
  };
  $.ajax({
    data: postData,
    success: function(data){
      var permObj = data['body'][member];
      permObj[type]['access'] = access;
      if (access == 'exclude') {
        permObj[type]['value'] = new Array();//going from whitelist to blacklist, i guess we can include everyone
      } else {
        permObj[type]['value'] = [$('#ident_id').val()];//going from blacklist to whitelist, in the very least requires one person, in this case the ident of the togglemonkey
      }
      eval('var formData = JSON.stringify({ ' + member + ' : permObj })');
      var postData = {
        "url" : "/" + obj + "/" + objId + "/" + member,
        "method" : "POST",
        "data" : formData
      };
      $.ajax({
        data: postData,
        success: function(data){
          loadPermissionsObject(tabTarget,obj,objId,member);
        },
        error: function(xhr){
          alert('error updating permissions access');
        }
      });
    },
    error: function(xhr){
      alert('error getting permissions template');
    }
  });
}
function submitPermissionsAdd(tabTarget,obj,objId,member) {
  var postData = {
    "url" : "/" + obj + "/" + objId + "/" + member + "?hints=0",
    "method" : "GET",
    "ctype" : "json"
  };
  $.ajax({
    data: postData,
    success: function(data){
      var permObj = data['body'][member];
      idArray = $('#'+objId+member+'IdentitiesToAdd' ).val().split(",");
      if ($('#'+objId+member+'read' ).attr('checked')) {
        for (var x = 0, y = idArray.length; x < y; x++) {
          permObj['read']['value'].push(idArray[x]);
        }
      }
      if ($('#'+objId+member+'write' ).attr('checked')) {
        for (var x = 0, y = idArray.length; x < y; x++) {
          permObj['write']['value'].push(idArray[x]);
        }
      }
      if ($('#'+objId+member+'delete' ).attr('checked')) {
        for (var x = 0, y = idArray.length; x < y; x++) {
          permObj['delete']['value'].push(idArray[x]);
        }
      }
      var formData = {};
      formData[member] = permObj;
      formData = JSON.stringify(formData);
      var postData = {
        "url" : "/" + obj + "/" + objId + "/" + member,
        "method" : "POST",
        "data" : formData
      };
      $.ajax({
        data: postData,
        success: function(data){
          $('#' + objId + member + 'AddIdentity').hide();
          loadPermissionsObject(tabTarget,obj,objId,member);
        },
        error: function(xhr){
          alert('error updating permissions template');
        }
      });
    },
    error: function(xhr){
      alert('error getting permissions template');
    }
  });
}
function submitPermissionRemove(tabTarget,identity,type,obj,objId,member) {
  var postData = {
    "url" : "/" + obj + "/" + objId + "/" + member + "?hints=0",
    "method" : "GET",
    "ctype" : "json"
  };
  $.ajax({
    data: postData,
    success: function(data){
      var permObj = data['body'][member];
      var formData = {};
      for (var x = 0, y = permObj[type]['value'].length; x < y; x++){
        if (permObj[type]['value'][x] == identity) {
          permObj[type]['value'].splice(x,1);
          break;
        }
      }
      formData[member] = permObj;
      var postData = {
        "url" : "/" + obj + "/" + objId + "/" + member,
        "method" : "POST",
        "data" : JSON.stringify(formData)
      };
      $.ajax({
        data: postData,
        success: function(data){
          loadPermissionsObject(tabTarget,obj,objId,member);
        },
        error: function(xhr){
          alert('error updating permissions template');
        }
      });
    },
    error: function(xhr){
      alert('error getting permissions template');
    }
  });
}


////////////////////////////
// STATISTICS
////////////////////////////


function doStatsChartModule(objectType,objectId,level,year,month,day) {
  var loadurl = "/control-panel/statisticsChartModule.html?objectType=" + objectType + "&objectId=" + objectId + "&level=" + level;
  if (undefined != year) {
    loadurl += "&year=" + year;
  }
  if (undefined != month) {
    loadurl += "&month=" + month;
  }
  if (undefined != day) {
    loadurl += "&day=" + day
  }
  $("#" + objectId + "stats").load(loadurl);
  //the statisticsChartModule will redraw the chart and render the ui for it
}

function updateChartsModule(objectType,objectId,level){
  if (level == 'MONTH') {
    doStatsChartModule(objectType,objectId,level,$('#' + objectId + 'YearSelect option:selected').val());
  } else if (level == 'DAY') {
    doStatsChartModule(objectType,objectId,level,$('#' + objectId + 'YearSelect option:selected').val(),$('#' + objectId + 'MonthSelect option:selected').val());
  } else if (level == 'HOUR') {
    doStatsChartModule(objectType,objectId,level,$('#' + objectId + 'YearSelect option:selected').val(),$('#' + objectId + 'MonthSelect option:selected').val(),$('#' + objectId + 'DaySelect').val());
  }
}



////////////////////////////
// TASKS
////////////////////////////

function doTaskListModule(creatorId){
  var targetId = '#' + creatorId + 'TaskItems';
  $(targetId).removeClass('ui-state-error').html($('#loading').html());
  $(targetId + ' > div').prepend('<h1>loading task list module...</h1>');
  $(targetId).load('/control-panel/taskListModule.html?creatorId=' + creatorId);
  targetId = '#' + creatorId + 'TaskList';
  $(targetId).show();
}

function taskHandler(creatorId, simulate, source, taskId) {
  var formData = {};
  if (undefined != taskId) {
    formData['taskId'] = taskId;
    formData['method'] = 'PUT';
  } else {
    formData['method'] = 'POST';
  }
  formData['source'] = editor.getSession().getValue();
  formData['creatorId'] = creatorId;
  formData['url'] = (simulate ? '/import/task/simulator' : '/import/task');
  $.ajax({
      url: '/import/taskHandler/',
      method: 'POST',
      data: formData,
      success: function(data){
        requestSuccessHandler(data);
        if (simulate) {
          doTaskSimulatorResponse(data);
        } else {
          window.location.href = '/import/' + data.body.id + '/' + creatorId;
        }
      },
      error: function(xhr){
        doTaskSimulatorResponse(JSON.parse(xhr.responseText));
      }
  });
}

function doTaskSimulatorResponse(data) {
  if (data.head.ok) {
    $('#input').html('').removeClass('ui-widget-content ui-state-error ui-corner-all p5').text(data.body.input);
    $('#output').html('').text(data.body.output);
    $('#simulatorResponse').dialog({
      modal: true,
      resizable: true,
      dialogClass: 'dlg',
      title: 'Task Simulator Response | Attempted: ' + data.body.drops.attempted + ' | Parsed: ' + data.body.drops.parsed + ' | Saved: ' + data.body.drops.saved,
      width: 800,
      height: 600,
      buttons: {
        "Close" : function() {
          $(this).dialog('close');
        }
      }
    });
  } else {
    $('#input').html('').addClass('ui-widget-content ui-state-error ui-corner-all p5');
    for (var x = 0, y = data.head.errors.length; x < y; x++){
      $('#input').append('<div>' + data.head.errors[x][1] + '</div>');
    }
    $('#simulatorResponse').dialog({
      modal: true,
      resizable: true,
      dialogClass: 'dlg',
      title: 'Task Simulator Error',
      width: 800,
      height: 250,
      buttons: {
        "Close" : function() {
          $(this).dialog('close');
        }
      }
    });
  }
}

function taskDeleteConfirm(creatorId,taskId){
  $('#taskDeleteText').show();
  $('#taskDeleteError').hide();
  $('#taskDeleteSuccess').hide();
  $('#taskDeleteConfirm').dialog({
    modal: true,
    resizable: true,
    dialogClass: 'dlg',
    width: 400,
    height: 200,
    buttons: [
      {
        text: "Delete Forever",
        priority: "primary",
        classes: "ui-priority-primary",
        click: function() {
          var formData = {};
          formData['taskId'] = taskId;
          formData['creatorId'] = creatorId;
          formData['url'] = '/import/task';
          formData['method'] = 'DELETE';
          $.ajax({
              url: '/import/taskHandler/',
              method: 'POST',
              data: formData,
              success: function(data){
                $('#taskDeleteText').hide();
                $('#taskDeleteError').hide();
                $('#taskDeleteSuccess').show();
                window.setTimeout(function() {  
                    window.location.href = '/import';  
                }, 2000);  
              },
              error: function(xhr){
                $('#taskDeleteText').hide();
                $('#taskDeleteSuccess').hide();
                $('#taskDeleteError').show();
              }
          });
        }
      },
      {
        text: "Cancel",
        priority: "secondary",
        classes: "ui-priority-secondary",
        click: function() { 
          $(this).dialog('close')
        }
      }
    ]
  });
}

/*
 * Superfish v1.4.8 - jQuery menu widget
 * Copyright (c) 2008 Joel Birch
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 *
 * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
 */

;(function($){
	$.fn.superfish = function(op){

		var sf = $.fn.superfish,
			c = sf.c,
			$arrow = $(['<span class="',c.arrowClass,'"> &#9660;</span>'].join('')),
			over = function(){
				var $$ = $(this), menu = getMenu($$);
				clearTimeout(menu.sfTimer);
				$$.showSuperfishUl().siblings().hideSuperfishUl();
			},
			out = function(){
				var $$ = $(this), menu = getMenu($$), o = sf.op;
				clearTimeout(menu.sfTimer);
				menu.sfTimer=setTimeout(function(){
					o.retainPath=($.inArray($$[0],o.$path)>-1);
					$$.hideSuperfishUl();
					if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
				},o.delay);	
			},
			getMenu = function($menu){
				var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
				sf.op = sf.o[menu.serial];
				return menu;
			},
			addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };
			
		return this.each(function() {
			var s = this.serial = sf.o.length;
			var o = $.extend({},sf.defaults,op);
			o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
				$(this).addClass([o.hoverClass,c.bcClass].join(' '))
					.filter('li:has(ul)').removeClass(o.pathClass);
			});
			sf.o[s] = sf.op = o;
			
			$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
				if (o.autoArrows) addArrow( $('>a:first-child',this) );
			})
			.not('.'+c.bcClass)
				.hideSuperfishUl();
			
			var $a = $('a',this);
			$a.each(function(i){
				var $li = $a.eq(i).parents('li');
				$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
			});
			o.onInit.call(this);
			
		}).each(function() {
			var menuClasses = [c.menuClass];
			if (sf.op.dropShadows  && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
			$(this).addClass(menuClasses.join(' '));
		});
	};

	var sf = $.fn.superfish;
	sf.o = [];
	sf.op = {};
	sf.IE7fix = function(){
		var o = sf.op;
		if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
			this.toggleClass(sf.c.shadowClass+'-off');
		};
	sf.c = {
		bcClass     : 'sf-breadcrumb',
		menuClass   : 'sf-js-enabled',
		anchorClass : 'sf-with-ul',
		arrowClass  : 'sf-sub-indicator',
		shadowClass : 'sf-shadow'
	};
	sf.defaults = {
		hoverClass	: 'sfHover',
		pathClass	: 'overideThisToUse',
		pathLevels	: 1,
		delay		: 800,
		animation	: {opacity:'show'},
		speed		: 'normal',
		autoArrows	: true,
		dropShadows : true,
		disableHI	: false,		// true disables hoverIntent detection
		onInit		: function(){}, // callback functions
		onBeforeShow: function(){},
		onShow		: function(){},
		onHide		: function(){}
	};
	$.fn.extend({
		hideSuperfishUl : function(){
			var o = sf.op,
				not = (o.retainPath===true) ? o.$path : '';
			o.retainPath = false;
			var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
					.find('>ul').hide().css('visibility','hidden');
			o.onHide.call($ul);
			return this;
		},
		showSuperfishUl : function(){
			var o = sf.op,
				sh = sf.c.shadowClass+'-off',
				$ul = this.addClass(o.hoverClass)
					.find('>ul:hidden').css('visibility','visible');
			sf.IE7fix.call($ul);
			o.onBeforeShow.call($ul);
			$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
			return this;
		}
	});

})(jQuery);

(function($){
/* hoverIntent by Brian Cherne */
$.fn.hoverIntent = function(f,g) {
// default configuration options
var cfg = {
sensitivity: 7,
interval: 100,
timeout: 0
};
// override configuration options with user supplied object
cfg = $.extend(cfg, g ? { over: f, out: g } : f );
// instantiate variables
// cX, cY = current X and Y position of mouse, updated by mousemove event
// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
var cX, cY, pX, pY;
// A private function for getting mouse position
var track = function(ev) {
cX = ev.pageX;
cY = ev.pageY;
};
// A private function for comparing current and previous mouse position
var compare = function(ev,ob) {
ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
// compare mouse positions to see if they've crossed the threshold
if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
$(ob).unbind("mousemove",track);
// set hoverIntent state to true (so mouseOut can be called)
ob.hoverIntent_s = 1;
return cfg.over.apply(ob,[ev]);
} else {
// set previous coordinates for next time
pX = cX; pY = cY;
// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
}
};
// A private function for delaying the mouseOut function
var delay = function(ev,ob) {
ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
ob.hoverIntent_s = 0;
return cfg.out.apply(ob,[ev]);
};
// A private function for handling mouse 'hovering'
var handleHover = function(e) {
// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
if ( p == this ) { return false; }
// copy objects to be passed into t (required for event object to be passed in IE)
var ev = jQuery.extend({},e);
var ob = this;
// cancel hoverIntent timer if it exists
if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }
// else e.type == "onmouseover"
if (e.type == "mouseover") {
// set "previous" X and Y position based on initial entry point
pX = ev.pageX; pY = ev.pageY;
// update "current" X and Y position based on mousemove
$(ob).bind("mousemove",track);
// start polling interval (self-calling timeout) to compare mouse coordinates over time
if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}
// else e.type == "onmouseout"
} else {
// unbind expensive mousemove event
$(ob).unbind("mousemove",track);
// if hoverIntent state is true, then call the mouseOut function after the specified delay
if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
}
};
// bind the function to the two event listeners
return this.mouseover(handleHover).mouseout(handleHover);
};
})(jQuery);



/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
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;
    }
};





$(document).ready(function(){ 
    $("ul.sf-menu").superfish();
    if($.browser.msie && $.browser.version < 8) {
      
    }
}); 

