/* Insert Pithy Header Here */
$(document).ready(function(){

	/* ctrl+s = save */
	$(window).keydown(function(event){
		if(event.ctrlKey && event.keyCode==83){ 	
		$('#edit-submit').click();
		return false;
		}
	});
	
	/* Login */
	if(document.getElementById('page-user')) { 
		cookieFactory();
		
	  //set or delete the cookie
	  $('#user-login .form-submit').click(function(){
	    if($('#edit-rememberMe').attr('checked') == true){
	      $.cookie( 'username', $('#edit-name').val(), { expires: 365} );
	    }else{
	      $.cookie( 'username', null);
	    }
	  });		
	}

  /* Source Module*/
 	$('.nodeSource a').click(function(){ $(this).next().toggle(); return false; })
	
	/* aSearch box */
  if(document.getElementById('edit-keys')){
		if($('#edit-keys').val() == ''){	$('#edit-keys').val('search').css({color:'#bbb'}); }
		
		//clear the form on textfield focus	
		$('#contentTop #edit-keys, .section-aSearch #edit-keys').focus(function(){ 
			if($('#edit-keys').val() == 'search'){ $('#edit-keys').val('').css({color:'#444'}); } 
		})
		
		$('#contentTop #edit-keys, .section-aSearch #edit-keys').keypress(function (e) {
			if(e.which == 13){ $('#edit-submit').click(); return false;}  //for IE.  Ugh.
		})
		
		//clear the form on submit
		$('#edit-submit').click(function(){ if($('#edit-keys').val() == 'search'){ $('#edit-keys').val('') } })

		$('.clearFilters').click(function(){
			$('.criterion option').attr('selected', 0);
			$('#filterList').html('');
			return false;
		})
	}

  /* newsfeed */
  if(document.getElementById('page-newsfeed') || document.getElementById('page-newsfeed-internal')){
    bindMouseEvents();
    $('.feedViewerLink a').click(function(){ feedViewer($(this)); return false; });
    $('.feedDefinitionCell a').click(function(){ feedDefinition($(this)); return false; });
    $('.messageCloser').click(function(){ $(this).parent().slideUp('normal'); return false; });
    $('#footer').after('<img id="newsfeedPrevewSpacer" height="800" width="1" src="/sites/all/themes/images/blank.gif" />');//padding for popups  BRING BACK LATER IN PAGE VEIW< NOT VIA JS, dipshit
  }

  if(document.getElementById('feedPreview') || document.getElementById('page-node-add-newsfeed') || document.getElementById('page-node-edit')){
    //correctTheView();
    $('.newsfeed_typechooser').click(function(){ feedTypeToggle($(this)); return false; }); //end click
    $('#feedPreview').click(function(){feedPreview(); return false; }); //end click
    $('.feedPreviewX').click(function(){ $('#feedPreviewResults').slideUp('normal'); }); //end click
    $('.searchTable input').focus(function(){ searchTableClear($(this));   });
  }

  /* Other */
	$('.documentation').click(function(){$(this).next().toggle().bgiframe(); return false;});
	$('.redx').click(function(){$(this).parent().hide(); return false;});

  $('#showallusers').click(function()
    {
      if($(this).html() == 'Show All'){
        $(this).html('Hide All');
        $('#allusers').html('<img class="ajaxloader" src="/sites/all/themes/images/ajax-loader-1.gif ">');
        $('#allusers').show();
        $('#allusers').css({width: "250px"});
        $('#edit-users').css({height: "178px"});

        $.ajax(
          {
            type: 'GET',
            url: '/aaccess/showallusers',
            success: function(successmsg)
              {
                if(successmsg != 'List Selection Failed'){
                  $('#allusers').html(successmsg);
                }else{
                  alert(successmsg);
                }
              },
            error: function(failuremsg){alert('List selection failed due to AJAX problem.');}
          }
        );//end ajax

      }else{
        $(this).html('Show All');
        $('#allusers').hide();
        $('#edit-users').css({height: "90px"});
        $('#editusers_td').css({width: "100%"});
      }
      return false;
    }
  ); //end click


  $('#togglechecks').click(function()
    {
      if($('#togglechecks').html() == 'Check All'){
        $(".rolestable .form-checkbox").attr('checked', true);
        $('#togglechecks').html('Uncheck All');
      }else{
        $(".rolestable .form-checkbox").attr('checked', false);
        $('#togglechecks').html('Check All');
      }
      return false;
    }
  ); //end click

  $('#selectusers').click(function()
    {
      var currenttext = $('#edit-users').val();
      var newtext = currenttext + $('#edit-selectusers').val();
      $('#edit-users').val(newtext);
      $('#edit-selectusers').val('');
      return false;
    }
  ); //end click

  $('#clearusers').click(function() { $('#edit-users').val(''); return false; }); //end click

  $('#edit-lists-del').change(function()
    {
      var lid = $(this).val();
      var lidurl = '/aaccess/listdelete/' + lid;
      if (confirm('Are you sure you\'d like to delete this list?')) {
        $.ajax(
          {
          type: 'GET',
          url: lidurl,
          success: function(successmsg)
            {
              alert(successmsg);
              if(successmsg != 'List Deletion Failed'){
                //d5 will yell at you if you remove an option
                //$('#edit-lists_del').removeOption(lid);
                //$('#edit-lists').removeOption(lid);
              }
            },
          error: function(failuremsg){alert('List Deletion Failed due to Ajax problem.');}
          }
        );//end ajax
      } //end if
    }
  ); //end change

  $('#edit-lists').change(function()
    {
      var lid = $(this).val();
      var lidurl = '/aaccess/listselect/' + lid;
      $.ajax(
        {
        type: 'GET',
        url: lidurl,
        success: function(successmsg)
          {
            if(successmsg != 'List Selection Failed'){
              $('#edit-users').val(successmsg);
            }else{
              alert(successmsg);
            }
          },
        error: function(failuremsg){alert('List selection failed due to AJAX problem.');}
        }
      );//end ajax
    }
  ); //end change


	//Single Page Toggle
	$('a.toggle').click(function(){ $(this).parent('h3').parent('div').next('div').toggle(); return false; });

	// Open All Portlets
	$('a#all_open').click(function()
		{
			$('div.nodebody:hidden').show();
			$('a#all_open:visible').hide();
			$('a#all_close:hidden').show();
			return false;
		}
	);

	// Close All Portlets
	$('a#all_close').click(function()
		{
			$('div.nodebody:visible').hide();
			$('a#all_close:visible').hide();
			$('a#all_open:hidden').show();
			return false;
		}
	);

	$('#edit-private').click(function()
		{
			if($('#adv_perms').is('.closed')){
			  $('#adv_perms').show();
			  //$('#adv_perms').slideDown('slow');
			  $('#adv_perms').removeClass('closed');
			}else{
			  $('#adv_perms').hide();
        //$('#adv_perms').slideUp('slow');
			  $('#adv_perms').addClass('closed');
			}

    }//end click
	);
	
	$().blockbarGet();

}); // end doc.ready


function cookieFactory(){
  document.getElementById('edit-name').focus(); 

  //if I've got a cookie, set my username and give the pwd field focus
  if($.cookie('username')){
		//also deletes the cookie if remember me isn't checked
    $('#edit-name').val($.cookie( 'username'));
    $('#edit-rememberMe').attr('checked', true);
    document.getElementById('edit-pass').focus(); 
  }else{
    document.getElementById('edit-name').focus();
  }
}

function blockbar_toggle(contentPane, parm2){
	
	//if I've just opened the pane, write the cookie, else delete it
	if( $('#'+contentPane).is(':visible') ){	
		$('#'+contentPane).hide(); //close specific
		$.cookie('blockbar', 'none', {expires: 21, path: '/'});		//no cookie
	}else{
		$('.blockbar-content').hide(); //close all
		$('#'+contentPane).show(); // open specific
		$.cookie('blockbar', contentPane, {expires: 21, path: '/'});			
	}
}

$.fn.blockbarGet = function(){
	var contentPane = $.cookie('blockbar');
	$('#'+contentPane).show();
}
/****************************************************************************************
                                  Newsfeed Functions
****************************************************************************************/

/*******************  DEF ***********************/
function feedDefinition(e){
  //e is the $ object
  var nid = e.parent().attr('id');
  var paneId = '#' + nid +'Pane';
  nid = nid.replace('definition','');
  var url = '/feed_definition/' + nid + '/1';

  $.ajax({
    type: 'GET',
    url: url,
    success: function(page) {
      if($(paneId).html() == ''){
        $(paneId).html(page);
        bindFeedDefX(nid);
      }else{
        $(paneId).html('');
      }
    }
  }); //end ajax
}

/*******************  VIEWER ***********************/
function feedViewer(e){
  //e is the $ object
  var url = e.attr('href') + '/0/ajax';
  var fvpId = e.parent().attr('id').replace('fvl','#fvp');
  var paneId = fvpId.replace('fvp','fvptd');
  var contents = $(fvpId).text();

  var statusId = fvpId.replace('#fvp', '');
  toggleStatus(1, statusId);

  //1)deactivate feeds 2)close any open panes 3)empty contents of all panes (for id="pager") 4)Make current active
  $('tr.activeFeed').removeClass('activeFeed');
  $('.feedViewerPane').not(paneId).addClass('closed');
  $('.feedViewerPane td').children().html('');
  $(fvpId).parent().parent().prev().addClass('activeFeed');

  //load if there's no content, otherwise, show or hide
  if(contents.length == 1 || contents.length == 0){
    $.ajax({
      type: 'GET',
      url: url,
      success: function(page) {
        $(fvpId).html(page);
        $(paneId).removeClass('closed');
        bindMouseEvents();
        bindPagerEvents();
        toggleStatus(0, statusId);
      }
    });
  }else{
    $(paneId).toggleClass('closed');
    toggleStatus(0, statusId);
  }
}


/*******************  PREVIEWS ***********************/
function feedPreviewItemToggler(){ $('.feedPreviewItemDetail').toggle(); }

function feedPreview(){
  var url;
  var urladdenda ='';

  if($('#edit-directURL').val() != ''){
    url = $('#edit-directURL').val();
  }else if($('#edit-searchtext').val() != ''){
    url = $('#edit-searchtext').val()
    urladdenda = '/1';
  }else{
    url = $('#edit-as_all').val() + '|' +$('#edit-as_within').val() + '|' + $('#edit-as_exact').val();
    url = url + '|' +$('#edit-as_any').val() + '|' +  $('#edit-as_source').val() + '|' + $('#edit-as_without').val() + '|' + $('#edit-as_location').val();
    urladdenda = '/0/1';
  }
  var sources = $('.searchsources input').sourceToString();
 	var filter = $('#edit-titleFilter').val();

  var ajaxLoader = '<center><img class="newsfeed_ajaxloader" src="/sites/all/themes/images/ajax-loader_1a.gif "></center>';
  $('#feedPreviewResults').show().html(ajaxLoader);
	
	//This is required or you can't preview things like "E & Y"	
	url= url.replace('&','%26');

  $.ajax({
    type: 'POST',
    url: '/proxy' + urladdenda,
    //data: 'sources=' + sources + 'url=' + url,
    data: 'sources=' + sources + '&url=' + url + '&filter=' + filter,
    success: function(page) {
      $('#feedPreviewResults').html(page).show();
      bindMouseEvents();
    }
  });
}

function feedTypeToggle(e){
  if(e.html() == '[Enter a Feed]'){
    $('#edit-searchtext').val('');
  }else{
    $('#edit-directURL').val('');
  }
  $('.newsfeed_type').toggle();
}

/*******************  HELPER FUNCTIONS  ***********************/

function reallyUnencode(string){
  for(i = 0; i < string.length; i++){
    if(string.substr(i,1) == '+'){string = string.replace('+',' ');}
    if(string.substr(i,6) == '&#039;'){string = string.replace('&#039;','\'');}
  }
  return string;
}

function addToUserlist(username) {
  username = reallyUnencode(username);
  var currenttext = $('#edit-users').val();
  var newtext = currenttext + username;
  $('#edit-users').val(newtext);
}



function bindMouseEvents(){
  $('.feed-item').mouseover(function(){ $(this).children('.feed-item-body').show().find('.feed-item-body-bottom img').imageFixer(); });
  $('.feed-item').mouseout(function() { $('.feed-item-body').hide(); });
  $('.feed-item-body').ieShiv();
}

$.fn.ieShiv = function(){
  this.each(
    function(){
      var div = '<div class="feed-item-blank"><img height="' + $(this).height() + '" width="450" src="/sites/all/themes/images/blank.gif"></div>';
      $(this).children('.feed-item-body-top').before(div);
    }
  );
  // hide all the previews
  $('.feed-item-body').hide();
}

$.fn.imageFixer = function(){
  this.each(
    function(){
      var w= $(this).width();
      if(w > 200){
        var h = $(this).height();
        var ratio = w/200;
        $(this).attr('width', '200');
        $(this).attr('height', h/ratio);
      }
    }
  );
}

function bindPagerEvents(){

  $('#pager a').click(function(e){
    var fvpID = '#' + $('#pager').parent().attr('id');
    var statusId = fvpID.replace('#fvp', '');
    toggleStatus(1, statusId);
    var url = $(this).attr('href');

    $.ajax({
      type: 'GET',
      url: url,
      success: function(page) {
        $(fvpID).html(''); //clear it out lest you have too many of the same ID!!
        $(fvpID).html(page);
        bindMouseEvents();
        bindPagerEvents();
        toggleStatus(0, statusId);
      }
    });

    return false;
    }
  );
}

function  toggleStatus(on, statusId){
  var statusTextId = '#statusText' + statusId;
  var statusImageId = '#statusImage' + statusId;

  if(on){
    $(statusTextId).addClass('closed');
    $(statusImageId).removeClass('closed');
  }else{
    $(statusTextId).removeClass('closed');
    $(statusImageId).addClass('closed');
  }
}

function bindFeedDefX(nid){
  $('.feedDefX').click(function(){
    var id = '#definition' + nid + 'Pane';
    $(id).html('');
  });
}

function searchTableClear(e){
   //e is the $ object
  if(e.attr('id') == 'edit-searchtext'){
    //$('.searchTable input:gt(0)').val('');
    $('.advSearchTable input').val('');
  }else{
    if(e.is('.form-checkbox')){
    }else{
      $('#edit-searchtext').val('');
    }
  }
}

$.fn.sourceToString = function(){
  var output = '';
  this.each(
    function(){
      if(this.checked){
        var id = $(this).attr('id');
        id = id.replace('edit-','');
        output = output + id + '|';
      }
    }
  );
  output = output.substr(output, output.length-1);
  return output;
}




/****************************************************************************************
                                  3rd Party
****************************************************************************************/


/** jQuery Cookie plugin */
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){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()}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{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]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break}}}return cookieValue}};
/* bgIframe Version 2.1.1 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(b($){$.m.E=$.m.g=b(s){h($.x.10&&/6.0/.I(D.B)){s=$.w({c:\'3\',5:\'3\',8:\'3\',d:\'3\',k:M,e:\'F:i;\'},s||{});C a=b(n){f n&&n.t==r?n+\'4\':n},p=\'<o Y="g"W="0"R="-1"e="\'+s.e+\'"\'+\'Q="P:O;N:L;z-H:-1;\'+(s.k!==i?\'G:J(K=\\\'0\\\');\':\'\')+\'c:\'+(s.c==\'3\'?\'7(((l(2.9.j.A)||0)*-1)+\\\'4\\\')\':a(s.c))+\';\'+\'5:\'+(s.5==\'3\'?\'7(((l(2.9.j.y)||0)*-1)+\\\'4\\\')\':a(s.5))+\';\'+\'8:\'+(s.8==\'3\'?\'7(2.9.S+\\\'4\\\')\':a(s.8))+\';\'+\'d:\'+(s.d==\'3\'?\'7(2.9.v+\\\'4\\\')\':a(s.d))+\';\'+\'"/>\';f 2.T(b(){h($(\'> o.g\',2).U==0)2.V(q.X(p),2.u)})}f 2}})(Z);',62,63,'||this|auto|px|left||expression|width|parentNode||function|top|height|src|return|bgiframe|if|false|currentStyle|opacity|parseInt|fn||iframe|html|document|Number||constructor|firstChild|offsetHeight|extend|browser|borderLeftWidth||borderTopWidth|userAgent|var|navigator|bgIframe|javascript|filter|index|test|Alpha|Opacity|absolute|true|position|block|display|style|tabindex|offsetWidth|each|length|insertBefore|frameborder|createElement|class|jQuery|msie'.split('|'),0,{}))
