$(document).ready(function() {

   $("button.btn").add("button.btnTrack").hover(btnActive,btnNotActive);

   $("#main_content").equalHeights(true);
   //$.blockUI.defaults.css = {};
      
   date_slider_init(); 
   credibility_slider_init(); 

   $("#btnSearch").click(function(e) {
      showBusy();
   });

   expand_collapse_init();
   more_docs_init();

   tooltip();  
   screenshotPreview();

   ui_init();
});

function stripTag(htmlstr){
   return htmlstr.replace(/(<([^>]+)>)/ig,"");
};

this.tooltip = function(){	
	/* CONFIG */		
		var xOffset = 10;
		var yOffset = 40;		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */		
	//$("a.btooltip").hover(function(e){
	$(".btooltip").hover(function(e){
		this.t = this.title;
		this.title = "";
		$("body").append("<p style='font-size:85%;' id='tooltip'>"+ this.t +"</p>");
		$("#tooltip")
			.css("top",(e.pageY - yOffset) + "px")
			.css("left",(e.pageX + xOffset) + "px")
			.css("z-index",999)
			.fadeIn("fast");		
        },
	function(){
		this.title = this.t;		
		$("#tooltip").remove();
        });	
	$(".btooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - yOffset) + "px")
			.css("left",(e.pageX + xOffset) + "px");
	});			
};

this.screenshotPreview = function(){	
	/* CONFIG */
		
		var xOffset = 50;
		var yOffset = 80;
		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
		
	/* END CONFIG */
	$("a.screenshot").hover(function(e){
		/*
                this.t = this.title;
		this.title = "";	
		var c = (this.t != "") ? "<br/>" + this.t : "";
                */
                c = "";
		$("body").append("<p id='screenshot'><img src='"+ this.rel +"' alt='getting snapshot...' />"+ c +"</p>");								 
		$("#screenshot")
			.css("top",(e.pageY - yOffset) + "px")
			.css("left",(e.pageX + xOffset) + "px")
			.fadeIn();						
        },
	function(){
		$("#screenshot").remove();
        });	
	$("a.screenshot").mousemove(function(e){
		$("#screenshot")
			.css("top",(e.pageY - yOffset) + "px")
			.css("left",(e.pageX + xOffset) + "px");
	});			
};

    //----------------------------------------------------------
    // trim - String prototype trim function
    //----------------------------------------------------------
    String.prototype.trim = function () {
        return this.replace(/^\s*/, "").replace(/\s*$/, "");
    };

    //----------------------------------------------------------
    // visualLength - getting visual length of string 
    //----------------------------------------------------------
    String.prototype.visualLength = function()
    {
        var ruler = document.getElementById('ruler');
        ruler.innerHTML = this;
        return ruler.offsetWidth;
    };

    //----------------------------------------------------------
    // trimToPx - trim string to proper visual width with elipsis
    //----------------------------------------------------------
    String.prototype.trimToPx = function(length)
    {
        var tmp = this;
        var trimmed = this;
        if (tmp.visualLength() > length)
        {
            trimmed += "...";
            while (trimmed.visualLength() > length)
            {
                tmp = tmp.substring(0, tmp.length-1);
                trimmed = tmp + "...";
            }
        }
        return trimmed;
    };


    function urlencode(str) {
        return escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
    };

    function replaceQueryString(url,param,value) {
        var re = new RegExp("([?|&])" + param + "=.*?(&|$)","i");
        if (url.match(re))
            return url.replace(re,'$1' + param + "=" + value + '$2');
        else
            return url + '&' + param + "=" + value;
    }
    function removeQueryString(url,param) {
        var re = new RegExp("([?|&])" + param + "=.*?(&|$)","i");
        if (url.match(re))
            return url.replace(re,'$1' + '$2');
        else
            return url;
    }

    function urlParam(name, defaultVal){
	 var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
         if (results==null)
            return defaultVal;
         else
	    return results[1];
    }
 
    function showBusy() {
            //$.blockUI({ message: '<h3>searching...one moment.</h3>' }); 
    }

    function strpos (haystack, needle, offset) {
        var i = (haystack+'').indexOf(needle, (offset ? offset : 0));
        return i === -1 ? false : i;
    }

this.date_slider_init = function(){	
      $("#date_slider").slider({
                range: "min",
                step: 1, 
                value: 8-urlParam('dr',0), 
                max: 8, 
                min: 0,
                change: function(event, ui) {
                   var val = 8-ui.value;
                   var currVal = urlParam('dr',0);
                   if (val==currVal){
                      $("div#byDatesDiv2 span.slider_label").removeClass('slider_scale_selected');
                      return false;
                   }
                   var url=location.href;
                   url = replaceQueryString(url,'dr',val);
                   url = replaceQueryString(url,'start',0);
                   window.location.href = url;
                   showBusy();
                },
                slide: function(event, ui) {
                   if (ui.value < 1) 
                      return false;
                   $("div#byDatesDiv2 span.slider_label").removeClass('slider_scale_selected');
                   var scale_id = '#slider_dr'+(9-ui.value);
                   $(scale_id).addClass('slider_scale_selected');
                },
                start: function(event, ui) {
                   if (ui.value < 1) 
                      return false;
                   $("div#byDatesDiv2 span.slider_label").removeClass('slider_scale_selected');
                   var scale_id = '#slider_dr'+(9-ui.value);
                   $(scale_id).addClass('slider_scale_selected');
                }
      });
};

this.credibility_slider_init = function(){
      var credval = $('#byCredsDiv2').attr('cred');
      if (credval==null) {
         credval = 1; // defaults to 'medium'
      }

      var scaleElem = '#slider_cred' + (2-credval);
      if ($(scaleElem).length > 0)
         $(scaleElem).addClass('curr_slider_scale');

      $("#cred_slider").slider({
                range: "min",
                step: 1, 
                value: 2-credval, 
                max: 2, 
                min: 0,
                change: function(event, ui) {
                   var val = 2-ui.value;
                   // var currVal = urlParam('cred',2);
                   var currVal = $('#byCredsDiv2').attr('cred');
                   if (val==currVal){
                      $("div#byCredsDiv2 span.slider_label").removeClass('slider_scale_selected');
                      return false;
                   }
                   var url=location.href;
                   url = replaceQueryString(url,'cred',val);
                   url = replaceQueryString(url,'start',0);
                   window.location.href = url;
                   showBusy();
                },
                slide: function(event, ui) {
                   $("div#byCredsDiv2 span.slider_label").removeClass('slider_scale_selected');
                   var scale_id = '#slider_cred'+ui.value;
                   $(scale_id).addClass('slider_scale_selected');
                },
                start: function(event, ui) {
                   $("div#byCredsDiv2 span.slider_label").removeClass('slider_scale_selected');
                   var scale_id = '#slider_cred'+ui.value;
                   $(scale_id).addClass('slider_scale_selected');
                }
      });
      if (credval != 2)
         $("#byCredsDiv2").animate({ backgroundColor: "#FFCC33"}, 1000).animate({ backgroundColor: "#FFFFFF"}, 1000).animate({ backgroundColor: "#FFCC33"}, 1000).animate({ backgroundColor: "#FFFFFF"}, 1000);
};

this.expand_collapse_init = function(){
   //----------------- EXPAND COLLAPSE SECION ------------------
	$("div#byTrackletsDiv div.collapse").hide();
	$("div#byUsersDiv div.collapse").hide();

        $('div.expand').click(function(e) {
           e.preventDefault();
           $(this).toggleClass('open').siblings().removeClass('open').end()
             .next('.collapse').slideToggle().siblings('.collapse:visible').slideUp();
           $("#main_content").equalHeights(true);
           return false;
        });

        $('div.expand2').click(function(e) {
           e.preventDefault();
           $(this).toggleClass('open').siblings().removeClass('open').end()
             .next('.new_status').next('.collapse').slideToggle().siblings('.collapse:visible').slideUp();
           $("#main_content").equalHeights(true);
           return false;
        });

	// making category and credibility expand by default at startup
        //$('div#byCategoriesDiv div.expand').click();
        //$('div#byCredsDiv div.expand').click();
        //$('div#byDatesDiv div.expand').click();

	// if there's only 1 item in div, just open it by default
        if ($('div#byUsersDiv').attr('count')==1)
           $('div#byUsersDiv div.expand').click();
        if ($('div#byTrackletsDiv').attr('count')==1)
           $('div#byTrackletsDiv div.expand').click();
   //----------------- 
};

/*-------------------------------------------------------------------- 
 * JQuery Plugin: "EqualHeights"
 * by:	Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com)
 *
 * Copyright (c) 2008 Filament Group
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Description: Compares the heights or widths of the top-level children of a provided element 
 		and sets their min-height to the tallest height (or width to widest width). Sets in em units 
 		by default if pxToEm() method is available.
 * Dependencies: jQuery library, pxToEm method	(article: 
		http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/)							  
 * Usage Example: $(element).equalHeights();
  		Optional: to set min-height in px, pass a true argument: $(element).equalHeights(true);
 * Version: 2.0, 08.01.2008
--------------------------------------------------------------------*/

$.fn.equalHeights = function(px) {
	$(this).each(function(){
		var currentTallest = 0;
		$(this).children().each(function(i){
			if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
		});
		//if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
		// for ie6, set height since min-height isn't supported
		if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
		$(this).children().css({'min-height': currentTallest}); 
	});
	return this;
};

this.more_docs_init = function(){
   $("a.more_docs, a.toggle_more_docs").live('click', function(e){
      e.preventDefault();
      var grouping_id=$(this).attr("gid");
      var excl_ids=$(this).attr("excl_ids");
      var dom_id='#'+$(this).attr("domid");
      var morelink = this;
      if ($(this).hasClass('more_docs')) {
         //var theQuery = urlencode($("input#q-sm")[0].value);
         var theQuery = $("input#q-sm")[0].value;
         $(this).removeClass('more_docs');
         $(this).addClass('toggle_more_docs');
         $(this).text('fetching...');
         var now = new Date();
         $.get("getitems.php", {q: theQuery, cf: 1, gid: grouping_id, excl_ids: excl_ids, ajax: 1, nt: (now.getTime())},  function(html){
            $(morelink).text('(hide smiliar items)');
            $(dom_id).hide().html(html).fadeIn(1000);

            // reinitializes all the ui events and redraw after ajax call
            tooltip();  
            other_results_ui_init();
            screenshot2_init();
            $("#main_content").equalHeights(true);
         });
      } else {
         $(dom_id).toggle();    
         if ($(dom_id).is(":visible")) {
            $(morelink).html('(hide similar items)');
            $(morelink).attr('title','click to hide');
         } else {
            $(morelink).html('<b>(view more similar items)</b>');
            $(morelink).attr('title','click to show');
         }
         $("#main_content").equalHeights(true);
      }
   });
};

this.ui_init = function(){

   $('div#pro_tracklet_promo1').click(function(e){
      e.preventDefault();
      window.location.href = '/premium/info';
      return false;
   });

   $('div#consumer_tracklet_promo1').click(function(e){
      e.preventDefault();
      window.location.href = '/catalog/basic';
      return false;
   });

   $('div.cred_counts').hover(function(e){	
      $("#byCredsDiv2").stop().animate({ backgroundColor: "#FFCC33"}, 300).animate({ backgroundColor: "#fff"}, 1000);
      $("div.cred_counts").stop().animate({ backgroundColor: "#FFCC33"}, 300).animate({ backgroundColor: "#f5f3ef"}, 1000);
    },
    function(){
      $("#byCredsDiv2").stop().animate({ backgroundColor: "#FFFFFF"}, 100);
      $("div.cred_counts").stop().animate({ backgroundColor: "#f5f3ef"}, 100);
   });

   $("*").keypress(function (e) {
       if(e.ctrlKey && e.which == 100) { // 'd' key
           if ($("input#q-sm").hasClass('debug_on')==false){
              $("input#q-sm").addClass('debug_on');
              $("form#queryForm").append('<input name="debug" type="hidden" value="1"/>');
           }
       }
   });

   $("#moreTrackletsDiv").hide();
   $("#moreCategoriesDiv").hide();
   $("#moreAqDiv").hide();
   $(".l_hideButton").hide();
   $(".r_hideButton").hide();
   $(".queryInput").focus();

   // fading the 'loading...' status text during iframe redirect to source link
   if ($("#loading").length > 0 ) {
      $("#loading").fadeTo(5000,1).fadeOut('slow', function(){ $(this).addClass('hidden'); });
   }

   // technically this is also covered in the onError=imgError(this) call within the 
   // <img> tag itself in right_column_view.php.  however, this is a 2nd level safety
   // net in the event that an image is taking a long time to connect, hence not generating
   // the error event to trigger imgError() yet, this function will cover that case and not
   // leave a broken image on the UI.
   $(window).bind('load', function() {
      $('img.ico').each(function() {
         if((typeof this.naturalWidth != "undefined" && this.naturalWidth == 0 ) 
	    || this.readyState == 'uninitialized' ) {
	    $(this).attr('src', 'img/space.gif');
	    $(this).attr('class','no_ico');
         }
      });
   });

   $("button.es2").live("click", function(e){
       var queryTerm = urlParam('q','<empty-query-term>');
       queryTerm = queryTerm.replace(/\+/g, ' ');
       queryTerm = decodeURIComponent(queryTerm);
       queryTerm = htmlspecialchars(queryTerm);
       Soruka.EmptySearch.Dialog.showEmptySearch(queryTerm);
       return false;
   });
   $("#lnkShareFeed").live("click", function(e){
       Soruka.ShareFeed.Dialog.showShareFeed();
       return false;
   });
   $("a.lnkNewsLetter").live("click", function(e){
       Soruka.NewsLetter.Dialog.showNewsLetter();
       return false;
   });

   /***********/
   // sign-out handler to attempt deleting IDENT cookie immediately as the follow-up 302 from /account/signout
   // immediately delete a cookie in a 302 redirect, causing the 'welcome abc' to still show up.
   /***********/
   $("a#signout").live("click", function(e){
      $.cookie('si',null);
   });

   /***********/
   // intercept a href from item title click to put it in iframe page
   /***********/
   $("a.frameit").live("click", function(e){
      e.preventDefault();
      var url=$(this).attr("href");
      if (strpos(url,'http://www.youtube.com/v/')===false) {
         var cqid=$(this).attr("cqid");
         var aqid=$(this).attr("aqid");
         var title=$(this).text();
         var returnUrl=location.href;
         var frameurl = "rd.php?url="+urlencode(url)+"&cqid="+cqid+"&aqid="+aqid+"&title="+title+"&rurl="+urlencode(returnUrl);
         window.open(frameurl,"_blank");
         return false;
      } else {
         var popwin = window.open(url, 'video', 'location=no,toolbar=no,menubar=no,status=no,width=600,height=338');
         popwin.focus();
         return false;
         //showMediaPlayer_popup(url);
      }
   });

   /***********/
   // 'more' button click for users
   /***********/
   $("a.moreUsers").click(function(e){
      e.preventDefault();
      $(".moreUsers").hide();
      $("#moreUsersDiv").fadeIn("slow");
      return false;
   });

   /***********/
   // 'more' button click for tracklets
   /***********/
   $("a.moreTracklets").click(function(e){
      e.preventDefault();
      $(".moreTracklets").hide();
      $("#moreTrackletsDiv").fadeIn("slow");
      return false;
   });

   /***********/
   // 'more' button click for categories
   /***********/
   $("a.moreCategories").click(function(e){
      e.preventDefault();
      $(".moreCategories").hide();
      $("#moreCategoriesDiv").fadeIn("slow");
      return false;
   });

   /***********/
   // 'more' button click for aq titles
   /***********/
   $("a.moreAq").click(function(e){
      e.preventDefault();
      $(".moreAq").hide();
      $("#moreAqDiv").fadeIn("slow");
      return false;
   });

   /***********/
   // mouseover for items
   /***********/
   $("li.item_li").hover(function(e){	
      $(this).addClass("item_selected");
      //$(this).find("tr > td > span.track_and_tweet").fadeIn("fast");

      // fade in hide/filter links
      $(this).find("table.innerAlertTable").find('a.filterOut' ).removeClass('filtergrey');

/*
      // fade in images within each alert
      $(this).find("table.alertTable img").stop().animate({ opacity: 1.0 }, 1);

      // fade in images within each metadata div
      $(this).find("div.meta_div img").stop().animate({ opacity: 1.0 }, 1);
*/
    },
    function(){
      $(this).removeClass("item_selected");
      //$(this).find("tr > td > span.track_and_tweet").hide();

      // fade out hide/filter links
      $(this).find("table.innerAlertTable").find('a.filterOut' ).addClass('filtergrey');

/*
      // fade out images within each alert
      $(this).find("table.alertTable img").stop().animate({ opacity: 0.7 }, 1);

      // fade out images within each metadata div
      $(this).find("div.meta_div img").stop().animate({ opacity: 0.7 }, 1);
*/
   });	

   /***********/
   // mouseover for categories, users, tracklets
   /***********/
/*
   $("li.usr_li, li.trk_li").hover(function(e){
      $(this).find("a.filterOut").removeClass('filtergrey');
      $(this).addClass("li_selected");
    },
    function(){
      $(this).find("a.filterOut").addClass('filtergrey');
      $(this).removeClass("li_selected");
   });	
*/
   /***********/
   // mouseover for aq titles
   /***********/
   $("li.aq_li").hover(function(e){										
      $(this).addClass("li_selected");
    },
    function(){
      $(this).removeClass("li_selected");
   });	

   $('a.collapse_cnt').click(function(e){
      e.preventDefault();
      var url=location.href;
      if (url.substring(url.length-1)=='#')    // if url ends with '#', then remove it 
         url = url.substring(0, url.length-1); // removing trailing '#' character
      var gid=$(this).attr('gid');
      url = replaceQueryString(url,'start',0);
      url = replaceQueryString(url,'cf_gid',gid);
      url = replaceQueryString(url,'cf','1');
      window.location.href = url;
      return false;
   });

   $('a.categoryName').click(function(e){
      e.preventDefault();
      $("input.cat_cbox").attr('checked',false);  // uncheck all cboxes
      var myparent=$(this).parent().parent(); // <div>
      var my_cb=myparent.children("input.cat_cbox"); // a.frameit
      my_cb[0].click();
   });

   $('input.cat_cbox').click(function(e){
      var catparam = '';
      var url=location.href;

      if ($(this).attr('cname')=='All' && $(this).attr('checked',true)) {
         // do nothing, forcing cname to be blank so we fetch 'All' categories. 
         $("input.cbox_non_all").attr('checked',false);  // uncheck all other non-ALL cboxes
      } else {
         $("input#cat_cb_all").attr('checked',false);
         $("input.cat_cbox[@type=checkbox][checked]").each( 
             function() { 
               catparam += '|';
               catparam += '"'+urlencode($(this).attr('cname'))+'"';
             } 
         );
      }
      if ($("input.cat_cbox[@type=checkbox][checked]").length==0)
         $("input#cat_cb_all").attr('checked',true);

      showBusy();
      catparam = catparam.substring(1);
      if (catparam!='')
         url = replaceQueryString(url,'cname',catparam);
      else
         url = removeQueryString(url,'cname');
      url = replaceQueryString(url,'start',0);
      window.location.href = url;
   });

    //EZPZ Hint v1.1.1; Copyright (c) 2009 Mike Enriquez, http://theezpzway.com; Released under the MIT License
    $.fn.ezpz_hint = function(options){
        var defaults = {
            hintClass: 'txtHeaderSearchHint',
            hintName: 'ezpz_hint_dummy_input'
        };
        var settings = $.extend(defaults, options);

        return this.each(function(){
            var hint;
            var dummy_input;

            // grab the input's title attribute
            text = $(this).attr('title');

            // create a dummy input and place it before the input
            //$('<input type="text" name="temp" value="" />').insertBefore($(this));
            $('<input type="text"  value="" />').insertBefore($(this));

            // set the dummy input's attributes
            hint = $(this).prev('input:first');
            hint.attr('class', $(this).attr('class'));
            hint.attr('size', $(this).attr('size'));
            //hint.attr('name', settings.hintName);
            hint.attr('autocomplete', 'off');
            hint.attr('tabIndex', $(this).attr('tabIndex'));
            hint.addClass(settings.hintClass);
            hint.val(text);

            // hide the input
            $(this).hide();

            // don't allow autocomplete (sorry, no remember password)
            $(this).attr('autocomplete', 'off');

            // bind focus event on the dummy input to swap with the real input
            hint.focus(function(){
                dummy_input = $(this);
                $(this).next('input:first').show();
                $(this).next('input:first').focus();
                $(this).next('input:first').unbind('blur').blur(function(){
                    if ($(this).val() == '') {
                        $(this).hide();
                        dummy_input.show();
                    }
                });
                $(this).hide();
            });

            // swap if there is a default value
            if ($(this).val() != ''){
                hint.focus();
            };

            // remove the dummy inputs so that they don't get submitted
            //$('form').submit(function(){
                //$('.' + settings.hintName).remove();
            //});
        });

    };
    $("input#txtHeaderSearch").ezpz_hint();
}

function btnActive() {
        $(this).addClass("active");
}
function btnNotActive() {
        $(this).removeClass("active");
}

function htmlspecialchars(p_string) {
	p_string = p_string.replace(/&/g, '&amp;');
	p_string = p_string.replace(/</g, '&lt;');
	p_string = p_string.replace(/>/g, '&gt;');
	p_string = p_string.replace(/"/g, '&quot;');
//	p_string = p_string.replace(/'/g, '&#039;');
	return p_string;
}

