/***************************************
****************************************
    GENERAL SCRIPTS
****************************************
***************************************/


/***************************************
    ON DOCUMENT LOAD
    ------------------------------------
    Any code between this function
    executs when the page had loaded
    fully.
***************************************/
$(document).ready(function()
{     	
    /*****************************/
	/******  school names    *****/
	/*****************************/
	$('marquee .pipe:last').remove();
    $('marquee').marquee('pointer').mouseover(function () {
            $(this).trigger('stop');
    }).mouseout(function () {
        $(this).trigger('start');
    }).mousemove(function (event) {
        if ($(this).data('drag') == true) {
            this.scrollLeft = $(this).data('scrollX') + ($(this).data('x') - event.clientX);
        }
    });
   
        
	/*****************************/
	/******  css help        *****/
	/*****************************/
	$("table tr:odd").addClass("odd");
    $("#menu2 li:last").css("border", "none");
    //$("#products h3 a").bigTarget(); //http://tinyurl.com/bigtarget
    //$("#relatedproducts ul h4 a").bigTarget();
    //$("#products .product, #relatedproducts .relateditem").css("cursor", "pointer");
    
    var colours = ["#E27A3B", "#3399CC", "#CC9900"]; //price colours
    $("#products .product h3 span").each(function(i, e) {
        $(this).css("color", colours[i%colours.length]);
    });
    

	/*****************************/
	/******  sirf            *****/
	/*****************************/
	$('h1, #rhs h3, #relatedproducts h3, #thankyou p').each(function() {
	    //$(this).html($(this).text());
	});
    $('#rhs h3').sifr({ font: 'font_back'}); 
    $('#relatedproducts h3, #thankyou p').sifr({ font: 'font'}); 
    
    $('h1').sifr({ font: 'font', forceSingleLine :false, preventWrap : false}); 
    
    
    /*$('#rhs h3').sifr({ font: 'font'});
    $('#relatedproducts h3').sifr({ font: 'font'});
    $('#thankyou p').sifr({ font: 'font'});*/


   
	/*****************************/
	/****** tool tips        *****/
	/*****************************/
    $(".logout").easyTooltip();
   
	/*****************************/
	/****** rounded corners  *****/
	/*****************************/
	//todo - check if not supported in css
	
	if(! ($.browser.msie && $.browser.version < 7)) {
	
        $(".simplecontrol").corner("10px");
        
        $(".usercontrol, .banner a, .img, #profilemenu, .corners,  #menu2 ul ul ").corner("10px");
        
        
        if( window.location.pathname.toLowerCase().indexOf("cart.aspx") == -1 &&
            window.location.pathname.toLowerCase().indexOf("mydetails.aspx") == -1 &&
            window.location.pathname.toLowerCase().indexOf("/products/") == -1  ) {
            $("#content").corner("10px");
        }
         
        
        
        $(".cartproductnameheader").corner("10px tl");
        $(".TableMyShoppingBag th:last").corner("10px tr");


	    $(".warning, 	.validation, 	#shp_error, 	#contactform .validation,	#Summary div ").corner("5px");


        //$(".simplecontrol span").corner("#000000 4px bevel overSized");
        
    
    }
    
    
	/*****************************/
	/******  menu            *****/
	/*****************************/
    $("#menu1 > ul > li").fadeMenu(300);
    $("#menu2 > ul > li").fadeMenu(300);

    
    /***************************************
        TABS
        ------------------------------------
        jQuery ui tabs was broken. 
        Temp code.
    ***************************************/
        //clear smooth scroll
        $(".tabs a").unbind("click");
        //hide tabs except for first
        $(".tabs").each(function() {
            $("> div", this).hide().eq(0).show();
            $("> ul li", this).eq(0).addClass("selected");
        });

        //on tab click
        $(".tabs .nav li a").click(
            function(e) {   
                var $tabs = $(this).parent().parent().parent();
                //remove classes and hide  
                $("> div", $tabs).hide()
                                .removeClass("selected");
                                
                $(".nav li", $tabs).removeClass("selected");
                
                $($(this).attr("href")).show()
                                       .addClass("selected");
                $(this).parent().addClass("selected");            
                
                e.preventDefault();
        });
        

   
	/*****************************/
	/******  preload images  *****/
	/*****************************/
	/*if (document.images)
	{
		pic1= new Image();
		pic1.src="/images/image.gif";
		pic2= new Image();
		pic2.src="/images/image.gif";
	}*/

   
   
   
	/*****************************/
	/******   smooth scroll  *****/
	/*****************************/
	/*doesn't play well with transitions*/
	//jQuery.localScroll();
	
	
	/*****************************/
	/******   pagination    *****/
	/*****************************/
    $(".paginate").each(function() {    
        //log($(".pagerButtons", this))
        $(" .newseventitem", this).quickpaginate({ perpage: 5, showcounter: true, pager : $(".pagerButtons", this) });
    });


	
	
	/*****************************/
	/**** error page           ***/
	/*****************************/	
	var $yahoo = $("#yahoosearch"),
		$output = $("#yahoosearchoutput");

	//developer.yahoo.com/search/boss/ 
	//http://developer.yahoo.com/common/json.html
	
	
	$("#error input.button").click(function(e) {
		$yahoo.css("background", "url(images/search_loading.gif) center center no-repeat");
		$output.html("");
		
		var query = $yahoo.val();
		var path  = "http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query="
					+query+"+site:outstandingschools.com&results=10&output=json";		    //////////////////FIX THIS DOMAIN
        $.ajax({
            url:       path,
            dataType:  'jsonp',
            success:   ws_results                	    
		}); 
	
	});
	

	function ws_results(data) {
		
		
		$output.empty();
		var r =  data.ResultSet;
		//log($yahoo, data);
		
		var html = "", 
			end = "";
		//html+="<p>Displaying the first " + parseInt(r.firstResultPosition) + " - " + (parseInt(r.firstResultPosition) + parseInt(r.totalResultsReturned)) + " from " + r.totalResultsAvailable + " results.</p><ul>";
		
		
		if (r.totalResultsAvailable == 0) {
			html="<p>Sorry, there are no results available for this query. Please try again.</p>";
		} else {
			html+="<p>Displaying " + r.totalResultsReturned + " results:</p><ul>";
			
			$.each(r.Result, function(i, result) {	
				
				if( i === r.totalResultsReturned-1) end = " class='last'";
				
				html += "<li" + end + "><h3><a href='"+result.Url+"'>"+result.Title+"</a></h3><p>"+result.Summary+"</p></li>";     
				if ( i === 9 ) return false;
			});		
	        
			html+="</ul>";         
        }      
        
        
        $output.append(html);        
		$yahoo.css("background", "");        
	}
	
	
	
	
	
	
	

});
   
/*****************************/
/******   libs           *****/
/*****************************/
$.fn.fadeMenu = function (t, selector) {      
    //ss(selector).remove();  
    
    

    
    if($.browser.msie && $.browser.version < 7) {
    
        return this.each(function() {
           // log(this);
            var $ul = $(this).find('ul:first');
            $ul.css("display", "none");
            $(this).hover(function(e){   
                    $ul.css("display", "block")  //try visiblity not display:none
                       .animate({opacity: 1}, { queue: false, duration: t });  
                },function(e){
                    $ul.css("display", "none")  
                       .animate({opacity: 0}, { queue: false, duration: t });                    
            });
        });
        
    } else {   
    
        return this.each(function() {
           // log(this);
            var $ul = $(this).find('ul:first');
            $ul.css("visiblity", "hidden");
            $(this).hover(function(e){   
                    $ul.css("visiblity", "visible")  //try visiblity not display:none
                       .animate({opacity: 1}, { queue: false, duration: t });  
                },function(e){
                    $ul.css("visiblity", "hidden")  
                       .animate({opacity: 0}, { queue: false, duration: t });  
                    
            });
        });
        
    }
    
    
    
    
};          

/*
 * 	Easy Tooltip 1.0 - jQuery plugin
 *	written by Alen Grakalic	
 *	http://cssglobe.com/post/4380/easy-tooltip--jquery-plugin
 *
 *	Copyright (c) 2009 Alen Grakalic (http://cssglobe.com)
 *	Dual licensed under the MIT (MIT-LICENSE.txt)
 *	and GPL (GPL-LICENSE.txt) licenses.
 *
 *	Built for jQuery library
 *	http://jquery.com
 *
 */
 
(function($) {

	$.fn.easyTooltip = function(options){
	  
		// default configuration properties
		var defaults = {	
			xOffset: 10,		
			yOffset: 25,
			tooltipId: "easyTooltip",
			clickRemove: false,
			content: "",
			useElement: ""
		}; 
			
		var options = $.extend(defaults, options);  
		var content;
				
		this.each(function() {
		    
		    
			var title = $(this).attr("title");				
			$(this).hover(function(e){											 							   
				content = (options.content != "") ? options.content : title;
				content = (options.useElement != "") ? $("#" + options.useElement).html() : content;
				$(this).attr("title","");									  				
				if (content != "" && content != undefined){			
					$("body").append("<div id='"+ options.tooltipId +"'>"+ content +"</div>");		
					$("#" + options.tooltipId)
						.css("position","absolute")
						.css("top",(e.pageY - options.yOffset) + "px")
						.css("left",(e.pageX + options.xOffset) + "px")						
						.css("display","none")
						.fadeIn("fast")
				}
			},
			function(){	
				$("#" + options.tooltipId).remove();
				$(this).attr("title",title);
			});	
			$(this).mousemove(function(e){
				$("#" + options.tooltipId)
					.css("top",(e.pageY - options.yOffset) + "px")
					.css("left",(e.pageX + options.xOffset) + "px")					
			});	
			if(options.clickRemove){
				$(this).mousedown(function(e){
					$("#" + options.tooltipId).remove();
					$(this).attr("title",title);
				});				
			}
		});
	  
	};

})(jQuery);

/* ===========================================================================
 *
 * JQuery Quick Pagination
 * Version 1.0.1
 * Quick and dirty pagination for pretty much any set of elements on the page.
 *
 * Author: Mark Perkins
 * Author email: mark@allmarkedup.com
 * For full documentation and more go to http://projects.allmarkedup.com/jquery_quick_paginate/
 *
 * ---------------------------------------------------------------------------
 *
 * LICENCE:
 *
 * Released under a MIT Licence. See licence.txt that should have been supplied with this file,
 * or visit http://projects.allmarkedup.com/jquery_quick_paginate/licence.txt
 *
 * ---------------------------------------------------------------------------
 * 
 * EXAMPLES OF USE:
 *
 * jQuery('.news_item').quickpaginate(); // would paginate all items on the page with the class of 'news_item'
 * 
 * jQuery('div#quick_slideshow img').quickpaginate(); // would paginate all img elements within the div with an id of 'quick_slideshow'
 *
 * // Paginate everything with the class of "news_item",
 * // 5 per 'page' and without the page counter.
 * jQuery('.news_item').quickpaginate( { perpage: 5, showcounter: false } ); 
 *
 * // Paginate all img elements and the element with the id of "info",
 * // with the prev/next/counter element appended to the element with the id of "pager_here"
 * jQuery('img, #info').quickpaginate({ pager : $("#pager_here") });
 *
 */

jQuery.fn.quickpaginate = function( settings ) {

	settings = jQuery.extend({
   
		perpage: 6,
		
		pager : null,
		
		showcounter : true,
		
		prev : "qp_next",

		next : "qp_prev",
		
		pagenumber : "qp_pagenumber",
		
		totalnumber : "qp_totalnumber",
		
		counter : "qp_counter"

	}, settings);

	var cm;
	
	var total;
	
	var last = false;
	
	var first = true;
	
	var items = jQuery(this);
	
	var nextbut;
	
	var prevbut;
	
	var init = function()
	{
		items.show();
		
		total = items.size();
				
		if ( items.size() > settings.perpage )
		{
			items.filter(":gt("+(settings.perpage-1)+")").hide();
			
			cm = settings.perpage;
			
			setNav();
		}
	};
	
	var goNext = function()
	{
		if ( !last )
		{
			var nm = cm + settings.perpage;
			items.hide();
			
			items.slice( cm, nm ).show();
			cm = nm;
			
			if ( cm >= total  )
			{
				last = true;
				nextbut.addClass("qp_disabled");
			}
			
			if ( settings.showcounter ) settings.pager.find("."+settings.pagenumber).text(cm/settings.perpage);
			
			prevbut.removeClass("qp_disabled");
			first = false;
		}
	};
	
	var goPrev = function()
	{
		if ( !first )
		{
			var nm = cm-settings.perpage;
			items.hide();
			
			items.slice( (nm - settings.perpage), nm ).show();
			cm = nm;
			
			if ( cm == settings.perpage  )
			{
				first = true;
				prevbut.addClass("qp_disabled");
			}
			
			if ( settings.showcounter ) settings.pager.find("."+settings.pagenumber).text(cm/settings.perpage);
			
			nextbut.removeClass("qp_disabled");
			last = false;
		}
	};
	
	var setNav = function()
	{
		if ( settings.pager === null )
		{	
			settings.pager = jQuery('<div class="qc_pager"></div>');
			items.eq( items.size() -1 ).after(settings.pager);
		}
		
		var pagerNav = $('<a class="'+settings.prev+'" href="#">&lt;</a><a class="'+settings.next+'" href="#">&gt;</a>');
		
		jQuery(settings.pager).append( pagerNav );
		
		if ( settings.showcounter )
		{
			var counter = '<span class="'+settings.counter+'"><span class="'+settings.pagenumber+'"></span> / <span class="'+settings.totalnumber+'"></span></span>';
			
			settings.pager.find("."+settings.prev).after( counter );
			
			settings.pager.find("."+settings.pagenumber).text( 1 );
			settings.pager.find("."+settings.totalnumber).text( Math.ceil(total / settings.perpage) );
		}

		nextbut = settings.pager.find("."+settings.next);
			
		prevbut = settings.pager.find("."+settings.prev);
		
		prevbut.addClass("qp_disabled");
		
		nextbut.click(function(){
			goNext();
			return false;
		});
		
		prevbut.click(function(){
			goPrev();
			return false;
		});
		
	};
	
	init(); // run the function
};


function log() {
    try {   
        var args = [];
        for(var i=0; i<arguments.length;i++)
            args.push("arguments["+i+"]");
            
        eval("console.log("+args.join(",")+")");
           
    }catch(e){}
}


