var causeURL;

$(document).ready(function() {
	/*  Searchbox */
	$("#searchString").focus();

    /* Set tab on load */
    if( $('input#search_t').val() ) {
        var id = $('input#search_t').val();
        $( 'ul#nav li#' + id ).addClass('active');
        if(id == 'webalt') {
          $( 'ul#nav li#web').addClass('active');
        }
    } else {
        // cant detect val so set web as default
        $( 'ul#nav li#web' ).addClass('active');
    }

    /* Header Tab Flicks */
    $('ul#nav li').click( function() {
        $('ul#nav li').removeClass('active');
        $(this).addClass('active');

        // if has id attribute (not easyfundraising link)
        if( $(this).attr('id') ) {
            $('input#search_t').val( $(this).attr('id') );
            if( $('input#searchString').val() != '' &&
                    $('input#searchString').val() != 'Enter your search term and start fundraising') {
                $('#searchForm').submit();
            }
		// $('#searchString').focus();
            return false;
        }
    });

    /* Header Tab Functionality */
    // clear default search vars
    $('#searchString').click( function() {
       if( $(this).val() == 'Enter your search term and start fundraising' ) {
           $(this).val('');
       }
    });
    
    $('#search-field').click( function() {
       if( $(this).val() == 'Enter cause name e.g. NSPCC, Rugeley Cricket Club' ) {
           $(this).val('');
       }
    });

    // Result link masking.
    $("a.outbound").each(function() {
    	var mask_link = $(this).attr('rev');
    	var track_link = $(this).attr('href');
    	$(this).attr('rev', track_link);
    	$(this).attr('href', mask_link);
    });
    $("a.outbound").mousedown(function() {
    	var track_link = $(this).attr('rev');
    	$(this).attr('href', track_link);
    	return true;
    });


    // home page find out more
    $('.btn-more').click( function(){
       if( $('.homemore').is(":visible") ) {
           $(this).css('background-image', 'url(/images/ico-arrow1.gif)');
           $('.homemore').fadeOut('fast');
       } else {
           $(this).css('background-image', 'url(/images/ico-arrow2.gif)');
           $('.homemore').fadeIn('fast');
       }
       return false;
    });

    // search cause form with ajax call
    $('.detail-search-frm').submit( function(event) {
    	event.preventDefault();
    	if(!causeURL) {
	    	$('.search-results-holder').hide();
	      	$('.loading').css('display', 'block');
	       var pg = 1;
	       var f = '';
	       var pstr = "/rpc/org-search.php";
	       var string = "action=filterOrgSearch&s=" + escape($('#search-field').val()) + "&f=" + f + "&pg=" + pg;
	        $.ajax({
	          url: pstr,
	          data: string,
	          type: "POST",
	          success: function(response){
	              $('.loading').css('display', 'none');
	              $('.search-results-holder').show();
	              $('#search-results').html(response);
	          }
	        });
	        // Blur search field so that suggestions are hidden.
	        $("#search-field").blur();
	        return false;
    	}
    });

    $('.detail-search-frm-popup').submit( function() {
    	$('.search-results-holder').hide();
      	$('.loading').css('display', 'block');
       var pg = 1;
       var f = '';
       var pstr = "/rpc/org-search.php";
       var string = "action=filterOrgSearch&s=" + escape($('#popup-search-field').val()) + "&f=" + f + "&pg=" + pg + "&pop=true";
        $.ajax({
          url: pstr,
          data: string,
          type: "POST",
          success: function(response){
              $('.loading').css('display', 'none');
              $('.search-results-holder').show();
              $('#popup-search-results').html(response);
          }
        });
       return false;
    });

    // submit contact form
    $('.btn-psubmit').click( function() {
        $(this).parents('form:first').submit();
        return false;
    });

    // homepage link
    $('.btn-homepage').click(function() {
        
        var url = 'http://www.easysearch.org.uk';

        if (document.all) {
            document.body.style.behavior = 'url(#default#homepage)';
            document.body.setHomePage(url);
        } else if (window.sidebar) {
        if (window.netscape) {
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            }
            catch(e) {
                alert("Sorry the web browser you are using does not permit setting the homepage from this link. Please set your homepage manually.");
                $('.btn-homepage').fadeOut('fast');
            }
        }
            var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
            prefs.setCharPref('browser.startup.homepage', url);
        }

        $('.btn-homepage').fadeOut('fast');
        return false;
    });

    // add to favourites
    $('.btn-fav').click(function() {

		var data = $(this).attr('rel');
		data = data.split("|");

		// If the browser is Internet Explorer
		if (document.all) {
			// Add to Favorites (Internet Explorer)
			window.external.AddFavorite(data[1],data[0])
		} else {
			// Add to Bookmarks (Mozilla Firefox)
			window.sidebar.addPanel(data[0], data[1], '');
		}
		return false;
    });

    // add search provider
    $('.btn-provider').click(function() {

        var data = $(this).attr('data');
        var base = $(this).attr('domain');

        str = navigator.appVersion;

        // alert for webkit browsers
        if (str.match("WebKit")) {
            alert('Sorry, easysearch browser integration only supports Firefox and Internet Explorer web browsers');
            return false;
        }

        if (str.match("MSIE ([0-9])")) version = str.match("MSIE ([0-9])");


        //Mozilla Support
        if ((typeof window.sidebar == "object") && (typeof window.sidebar.addSearchEngine == "function")) {
            window.sidebar.addSearchEngine(
                "http://" + base + "/Provider.src",  /* engine URL */
                "http://" + base + "/images/provider.gif",  /* icon URL */
                base,                                         /* engine name */
                "Web" );                                               /* category name */
            return false;

        //IE Support
        } else if ((typeof window.external == "object") && version['1'] >= 7) {

            window.external.AddSearchProvider('http://' + base + '/Provider.xml?name=' + data );
            return false;

        } else {
            document.location.href = '/provider_service/';
            return false;
        }

        return false;
    });
    
    // Search orgs popup.
    $("#search_org_link").colorbox({width:"770px", height:"580px", inline:true, href:"#causepopup"});
    $('#search_org_link').colorbox({onComplete:function(){
    	$("#popup-search-field").focus();
    }});

    $("#search_org_footer_link").colorbox({width:"770px", height:"580px", inline:true, href:"#causepopup"});
    $('#search_org_footer_link').colorbox({onComplete:function(){
    	$("#popup-search-field").focus();
    }});
    
    // Easylink popup
    $(".easylink_link").colorbox({
      width:"770px",
      height:"580px",
      inline:true,
      href:"#easylink_info"
    });
        
    // Cause statistics explanation popup.
    $("#stat_explanation").mouseover(function() {
    	var offset = $(this).offset();
    	$("#tooltip").css('display', 'block');
    	$("#tooltip").css('left', offset.left - 200);
    	$("#tooltip").css('top', offset.top + 15);
    });
    $("#stat_explanation").mouseout(function() {
    	$("#tooltip").css('display','none');
    });

    $("#advanced_row").hide();

    // Advanced preferences options reveal.
    $("#advanced_prefs").click(function() {
    	$("#advanced_row").toggle();
    	return false;
    });
    
    // Search autosuggest
    // mainSearchAutosuggest();

});

// Cause A-Z form with ajax call.
function fetchCauses(letter) {
	$('.search-results-holder').hide();
  	$('.loading').css('display', 'block');
  var pg = 1;
  var f = '';
  var pstr = "/rpc/org-search.php";
  var string = "action=filterOrgSearch&s=" + letter + "&f=" + f + "&pg=" + pg;
    $.ajax({
      url: pstr,
      data: string,
      type: "POST",
      success: function(response){
          $('.loading').css('display', 'none');
          $('.search-results-holder').show();
          $('#search-results').html(response);
        }
    });
    return false;
}

// Cause A-Z form with ajax call (for pop-up div).
function fetchCausesPop(letter) {
  $('.search-results-holder').hide();
    $('.loading').css('display', 'block');
  var pg = 1;
  var f = '';
  var pstr = "/rpc/org-search.php";
  var string = "action=filterOrgSearch&s=" + letter + "&f=" + f + "&pg=" + pg + "&pop=true";
    $.ajax({
      url: pstr,
      data: string,
      type: "POST",
      success: function(response){
          $('.loading').css('display', 'none');
          $('.search-results-holder').show();
          $('#popup-search-results').html(response);
        }
    });
    return false;
}

// Make homepage.
function makeHomepage(obj, url) {
  //Variables
  var pageName = "[ADDTOFAVS_TITLE]";
  var clientVersion = navigator.appVersion;

  //Set the home page
  if (clientVersion.indexOf('MSIE') != -1) {
    obj.style.behavior = "url(#default#homepage)";
    obj.setHomePage(url);
  } else {
    alert("Please set " + url + " \nas your home page using your browser settings.");
  }
}

// Function for tracking clicks from iOS.
function trackclickios( obj, e, url ) {
	$.ajax({
  		url: url,
  		async: false,
  		cache: false,
  		timeout: 3000,	// If the ajax request isn't complete after 3 seconds, it needs to forget tracking the link and carry on to the destination.
  		success: function(){
  			// alert('ajax success');
  			window.location.href = $(obj).attr('href');
		},
		error: function() {
			// alert('ajax failure');
           	window.location.href = $(obj).attr('href');
    	}
  	});
	return false;
}

// Function for tracking clicks.
function trackclick( obj, e, url ) {
	$.ajax({
		url: url,
		cache: false
	});
    return true;
}



// Parse the search XML and output either an unordered list with links (default) or populate an input value
function parseSearch(xml, resultListId, clickout, inputElement, word) {
    if ($.isXMLDoc(xml)) {
        var html = "<div id=\"suggestListContainer\"><ul class=\"non\">";
        var i = 0;
        $(xml).find('rs').each(function() {
          var result = $(this);
//          if ($(inputElement).length > 0) {
            // Build this list with no links
//            html += "<li><a rel=\"" + result.attr('dbid') + "\">" + result.text() + "</a></li>";
//          } else {
            // See where our clickout is, then replace %QUERY% with the result.text();
            var thisClickout = clickout;
            if (thisClickout.indexOf('%QUERY%') >= 0) {
              thisClickout = thisClickout.replace('%QUERY%', encodeURIComponent(result.text()));
            } else if (thisClickout.indexOf('%CAUSEURL%') >= 0) {
              thisClickout = thisClickout.replace('%CAUSEURL%', result.attr('causeurl'));
            } else if (thisClickout.indexOf('%ID%') >= 0) {
              thisClickout = thisClickout.replace('%ID%', result.attr('dbid'));
            }
            // Build this list item with a link
            html += "<li><a href=\"" + thisClickout + "\">" + result.text() + "</a></li>";
//          }
          i++;
        });
        //Specifically for homepage support your cause search
        if (i >= 10 && inputElement.attr("id") == "searchText") {
          html += "<li class=\"showOthers\"><a class=\"circleArrowRight\" href=\"/support-a-cause/?q="+encodeURIComponent(word)+"\">Show others for "+word+"</a></li>";
        }
        html += "</ul></div>";
        $(resultListId).html(html);
        // Add click events to list a tags if meant to populate an input
        if ($(inputElement).length > 0) {
          $(resultListId).contents().find("a").click(function() {
            $(inputElement).val($(this).text());
            //$(inputElement).siblings('input[type="hidden"]').val($(this).attr('rel'));
            $(resultListId).hide();
          });
        }
        $(resultListId).show();
    } else {
      $(resultListId).hide();
    }
}


// AJAX SEARCH
// function mainSearchAutosuggest(element) {
//   /* Main search auto suggest
//    * Usage:
//    * In the input HTML tag, we're hijacking the usemap attribute to store settings.
//    * We also need to apply a class to the input box which jQuery uses
//    * to apply behaviour.
//    * <input ... class="suggestiveSearch" usemap="suggestionSettings = {url: '/rpc/search/suggestions.php?type=cause', resultListId: '#suggestionsFindACause', clickout: '/find_a_cause/?q=%QUERY%'}" />
//    *
//    * The results are output to a div matching identifier in settings,
//    * "resultListId". Place this near your input box and use css to position it.
//    * <div id="searchSuggestions" class="searchSuggestions" style="display: none;"></div>
//   */
//   // On keyup fetch suggestions
//   var minimumCharacters = 2;

//   if (!element) {
//     element = $('input.suggestiveSearch');
//   }

//   element.keyup(function searchKeyup(e) {

//       // Fetch suggestion settings from the element (we've stored it in usemap var)
//       var suggestionSettings = null;
//       eval($(this).attr('usemap'));

//       // Setup our ajax call on the element
//       if (suggestionSettings) {

//         // Setup our behaviour on the box and search suggestion results
//         if (!$(this).attr('suggestionInit')) {

//           // On blur, hide
//           $(this).blur(function(e) {
//               if ($(suggestionSettings.resultListId + ':visible')) {

//                 // Make sure to only hide element if we're not hovering
//                 // over the suggestion box as we'll be making a click if
//                 // that's the case.
//                 //alert($('#searchSuggestions').attr('ignoreHide'));
//                 if ($(suggestionSettings.resultListId).attr('ignoreHide') != 'Yes') {
//                   $(suggestionSettings.resultListId).hide();
//                 }
//               }
//           });

//           // On hover ot search suggestions, makes sure to set a flag that stops
//           // the blur hide - else we'll hide the box before our click has actioned!
//           $(suggestionSettings.resultListId).hover(
//             function () {
//               $(suggestionSettings.resultListId).attr('ignoreHide', 'Yes');
//             },
//             function () {
//               $(suggestionSettings.resultListId).attr('ignoreHide', 'No');
//             }
//           );

//           // On focus show
//           $(this).focus(function(e) {
//               if ($(suggestionSettings.resultListId + ':hidden') && $(suggestionSettings.resultListId).val() > 1) {
//                   $(suggestionSettings.resultListId).show();
//               }
//           });

//           // Flag an attribute on the input so that we don't run this setup script again
//           $(this).attr('suggestionInit', true);

//         }

//         // Perform the search
//         var elem = $(this);
//         var word = $(this).val();
//         var searchUrl = suggestionSettings.url;
//         if(word.length < minimumCharacters) {
//           $(suggestionSettings.resultListId).hide();
//         } else {
//           if (e.keyCode != 40 && e.keyCode != 38) {
//             var suggestAjax = function() {
//               $.ajax({
//                 type: "GET",
//                 url: searchUrl,
//                 beforeSend: function() {
//                   elem.unbind("keyup");
//                 },
//                 data: ({'input':word}),
//                 dataType: "xml",
//                 success: function (xml) {
//                   elem.keyup(searchKeyup);
//                   $(suggestionSettings.resultListId).contents().find("a").unbind();
//                   if ($(xml).find('rs').length > 0) {
//                     parseSearch(xml, suggestionSettings.resultListId, suggestionSettings.clickout, elem, word);
//                   } else {
//                     $(suggestionSettings.resultListId).hide();
//                   }
//                   if (elem.val() != word && elem.val().length >= minimumCharacters) {
//                     word = elem.val(); 
//                     suggestAjax();
//                   } else if (elem.val().length < minimumCharacters) {
//                     $(suggestionSettings.resultListId).hide();
//                   }
//                 }
//               });
//             }
//             suggestAjax();
//           }
//         }

//         // Remove hover class from list links on hover
//         $(this).parent().siblings('.searchSuggestions').hover(function () {$(this).find('a.hover').removeClass('hover');});


//         // Scroll up and down list on keypress
//         if (e.keyCode == 40 || e.keyCode == 38) { // Down Arrow

//           // If we're already traversing the list
//           if ($(this).parent().siblings('.searchSuggestions').find('a.hover').length > 0) {
//             var currentHover = $(this).parent().siblings('.searchSuggestions').find('a.hover');

//             switch (e.keyCode) {

//               case 40: // Down Arrow
//                 var newHover = currentHover.parent('li').next().children('a');
//                 newHover.addClass('hover'); //Highlight next record
//                 $(this).val(newHover.html());
//                 causeURL = newHover.attr('href');
//                 break;

//               case 38: // Up Arrow
//                 var newHover = currentHover.parent('li').prev().children('a');
//                 newHover.addClass('hover'); //Highlight prev record
//                 $(this).val(newHover.html());
//                 causeURL = newHover.attr('href');
//                 break;
//             }

//             // Un-highlight current
//             currentHover.removeClass('hover');

//           // Set the first item in list to hover
//           } else {
//             var newHover = $(this).parent().siblings('.searchSuggestions').find('a').eq(0);
//             newHover.addClass('hover');
//             $(this).val(newHover.html());
//             causeURL = newHover.attr('href');
//           }
      
//   		}

//   		// Check if the user presses return.
//       	if (e.keyCode == 13) {
//       		// If a cause URL is set, send them to it.
// 	      	if(causeURL.length > 0) {
// 	      		window.location = causeURL;
// 	      	}
//       	}


//       }

//   });
// }

(function($) {

  $.fn.konami = function(callback, code) {
    if(code == undefined) code = "38,38,40,40,37,39,37,39,66,65";
    
    return this.each(function() {
      var kkeys = [];
      $(this).keydown(function(e){
        kkeys.push( e.keyCode );
        if ( kkeys.toString().indexOf( code ) >= 0 ){
          $(this).unbind('keydown', arguments.callee);
          callback(e);
        }
      }, true);
    });
  }

})(jQuery);

$(window).konami(function(){
    $("#wrapper").prepend('<img src="/images/nyancat.png" id="nyancat" style="z-index: 10; position: absolute;" />');
    $("#wrapper").append('<div id="nyan_loop"><embed src="/js/nyan-looped.mp3" hidden=true autostart=true loop=true></div>');
    $("#wrapper").css('position', 'relative');
    $("#nyancat").animate({
        width: "600",
        top: "50",
        left: "160"
    }, 1500 );
    for(var i = 0; i < 10; i++) {
        if(i%2 == 0) {
            $("#nyancat").animate({
              top: "60"
            });
        } else {
            $("#nyancat").animate({
              top: "50"
            });
        }
    }
    for(var i = 0; i < 30; i++) {
        if(i%2 == 0) {
            $("#nyancat").animate({
              top: "60",
              left: "+=50"
            });
        } else {
            $("#nyancat").animate({
              top: "50",
              left: "+=50"
            });
        }
    }
});
