$(function(){
	/* Use hoverIntent plugin for menu functionality */
	$("#menu li.menu-buy").hoverIntent({
		over: showDropdown, 
		timeout: 200, 
		out: hideDropdown
	});

	/* Stop search box events bubbling to list item */
	$('#search').hover(function(event){
		event.stopPropagation();
	});
				
	/* panel tabbed content functionality */
	
	if($('.panel .tabcontent').length) {
		$.each($('.panel .panel-content'),function(i){
			$(this).children('.tabcontent:not(:first)').css('display','none');
		});
		$('.tabs li').delegate('a','click',function() {
			var $this = $(this);
			$this.closest('li').siblings().removeClass('selected');
			$this.parent().addClass('selected');
							
			$this.parents(".panel:first").find(".tabcontent").hide();
			var $panel = $($this.attr("href")).show();
			return false;
		});
	}
	
	$('.tabs.tab-links li').delegate('a','click',function(e){
		window.location.href = $(this).attr('href');
	});
	
	$('.search-text').focus(function(){
		if($('#search-cat-dropdown').css('display') == 'block') {					// is the search category dropdown visible?
        	//hideCustomSelect();
			return false;
        }
		$(this).data('origText',$(this).val());
		$('.search-label').text('');
		
	}).blur(function() {
		if($(this).val() == "" && $(this).data('origText') == '' || $(this).val() == '') {
			$('.search-label').text('Search');
		}				
	});
	
	$('#search').delegate('.search-label','click',function(){
		$('.search-text').focus();
	});
	
	$(document).click(function(event) {
		// assign var to check if clicked element is within the search container
		var test = $(event.target).parents().index($('#search'));
	    if($(event.target).parents().index($('#search')) == -1) {					// clicked element is not a child of the search container
	        if($('#search-cat-dropdown').css('display') == 'block') {				// is the search category dropdown visible?
	        	hideCustomSelect();
				return false;
	        }
	    }        
	});

	/* search input - stop events bubbling */
	$('#search').delegate('input','hover',function(){
		
	});
	
	/* search select box dropdown */
	$('#search-cat').click(function() {
		$(this).toggleClass('selected');
		$('#search-cat-dropdown').toggle();
	});
	
	$('#search').delegate('input','',function(){
		
	});
		
	// set default category to be all
	//$('#search-cat').val('All Categories');
	//$('#search-cat').attr('title','0');
	
	$('#search-cat-dropdown').delegate('a','click',function(e){
		e.stopPropagation();
		$('#search-cat').attr('readonly','');
		var theText = $(this).text();
		var theValue = $(this).attr('title');
		
		$('#search-cat').val(theText);
		$('#category_id').val(theValue);
		
		$('#search-cat').attr('readonly','readonly');
		$('#search-cat').removeClass('selected');
		$('#search-cat-dropdown').hide();
		return false;
	});
	
	// LISTEN TO ALL CLICK HANDLERS ON HTML ELEMENT 
	// AND CLOSE SEARCH CATEGORY DROPDOWN IF CLICK DETECTED
	
	// APPLY SCROLL TO TOP
	$('.return-to-top').scrollToTop();
	
	/* CAROUSEL FUNCTIONALITY */
	$('.carousel-prev').click(function() {
		return false;
	});
	$('.carousel-next').click(function(e){
		return false;
	});
	
	/* SEARCH RESULTS PAGE FUNCTIONALITY */

	// hover over a search item row - Will be redundant when new search page is implemeneted
	if (!$.browser.msie || parseFloat($.browser.version) > 7) {
	    $('.search-item').delegate('td','hover',function(e) {
		    var $thisRow = $(this).closest('tr');
		    if(e.type == 'mouseenter') {
			    $thisRow.addClass('row-hover');
		    }
		    if(e.type == 'mouseleave') {
			    $thisRow.removeClass('row-hover');
		    }
	    });
	    $('.search-results').delegate('.search-item-gallery','hover',function(e){
		    if(e.type == 'mouseenter') {
			    $(this).addClass('cell-hover');
		    }
		    if(e.type == 'mouseleave') {
			    $(this).removeClass('cell-hover');
		    }
	    });
	}

	$('.login-to-watchlist').click(function(ev) {
		$.modal('<iframe src="/register/user_Login.aspx" height="400" width="785" scrolling="no" style="border:0"></iframe>', {
	        closeHTML: "",
	        containerCss: {
	            backgroundColor: "#fff",
	            height: 400,
	            padding: 0,
	            width: 785
	        },
	        overlayClose: true
	    });
	    ev.preventDefault();
	});

	$('.item-to-watchlist').click(function(ev) {
        var ele = $(this),
        	parent = ele.parent();
        $.get("/ajax/add_to_watchlist.aspx?itemid=" + ele.attr("rel") + "&r=" + Math.floor(Math.random() * 10000), function(data) {
            if (data != "") {
                ele.replaceWith("Watching");
                parent.removeClass('actionable watch-this').addClass('watch-this-watching');
            }
        });
        ev.preventDefault();
    });
	

	
	
	// FOCUS FIELDS
	if($('#sale-fee-calc .final-price').length) {
		focusInOut('#sale-fee-calc .final-price');
	}
	if($('#sell-landing-top .sell-keyword').length) {
		focusInOut('#sell-landing-top .sell-keyword');
	}
	
	/* FIX FOR SUBMIT INPUT ELEMENTS WITH BACKGROUND HOVER TO WORK ON ALL BROWSERS */
	$('.btn-keyword-submit,.btn-calc-submit').hover(
	function(){
		$(this).css('background-position-y','-29px');
	},
	function(){
		$(this).css('background-position-y','0');
	});
	
	$('body').delegate('.justlisted','hover',function(e){
		if(e.type == 'mouseenter') {
			changeOpacity($(this).find('img'),0.75);
		}
		if(e.type == 'mouseleave') {
			changeOpacity($(this).find('img'),1);
		}
	});
	
	$('#popular_searches').delegate('.row_cell','hover',function(e){
		if(e.type == 'mouseenter') {
			changeOpacity($(this).find('img'),0.75);
		}
		if(e.type == 'mouseleave') {
			changeOpacity($(this).find('img'),1);
		}
	});
	
	$('table').delegate('.recentlyviewed','hover',function(e){
		if(e.type == 'mouseenter') {
			changeOpacity($(this).find('img'),0.75);
		}
		if(e.type == 'mouseleave') {
			changeOpacity($(this).find('img'),1);
		}
	});
	
	
	/*
		ITEM DETAILS COUNTDOWN TIMER
		Check how long item is on auction for then display countdown timer
		If Auction has ended, display 'Auction ended' message
		TODO: Append auction end date to ended message if required
	*/
	
	if($('.countdown').length) {

	    var itemID = $("#itemid").val();
		$.ajax({
			type	: 'GET',
			url		: '/ajax/get_time_remaining.aspx',
			data	: 'itemid=' + itemID,
			success: function(data) {
				var timeArray = data.split(':');
				var countdownTime = '+'+ timeArray[0] + 'd +' + timeArray[1] + 'h +' + timeArray[2] + 'm +' + timeArray[3] + 's';
				if(timeArray[0] == '0' && timeArray[1] == '0' && timeArray[2] == '0' && timeArray[3] == '0') {
					$('.countdown').html('<span class="item-auction-ended">Auction ended</span>');
	            }
	            else if (timeArray[0] == '-1' && timeArray[1] == '-1' && timeArray[2] == '-1' && timeArray[3] == '-1') {
	                $('.countdown').html('');
	            }
	            else {
					$('.countdown').countdown({
						until: countdownTime,
						format: 'DHMS',
						layout:  
						'<ul id="countdown-timer">' +
							'<li class="bold green">Time Remaining</li>' +
							'<li class="digits">' +
								'<span class="timer-days1">{dnn}</span>' +
								'd' +
								'<span class="timer-separator">:</span>' +
								'<span class="timer-hour1">{hnn}</span>' +
								'h' +
								'<span class="timer-separator">:</span>' +
								'<span class="timer-mins1">{mnn}</span>' +
								'min' +
								'<span class="timer-separator">:</span>' +
								'<span class="timer-seconds1">{snn}</span>' +
								'secs' +
							'</li>' +
						'</ul>'
					});
				}
			},
			error	: function(e) {
			}
		});
	}
	
	/* JUST LISTED TABLE */
	$('.justlistedwithcategory_ascx .product-items').delegate('.product-item','hover',function(e){
		if(e.type == 'mouseenter') {
			$(this).addClass('cell-hover');
		}
		if(e.type == 'mouseleave'){
			$(this).removeClass('cell-hover');
		}
	});
});

// GET QUERY VARIABLE BY NAME
function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return null;
}

// Show top menu 'buy' dropdown
function showDropdown() {
	$('#menu li.menu-buy').addClass('menu-hover');
	$('#dropdown').addClass('dropdown-show');
}

// Hide top menu 'buy' dropdown
function hideDropdown() {
	$('#menu li.menu-buy').removeClass('menu-hover');
	$('#dropdown').removeClass('dropdown-show');
}

function hideCustomSelect() {
	$('#search-cat').attr('readonly','readonly');
	$('#search-cat').removeClass('selected');
	$('#search-cat-dropdown').hide();
}

/* PAGE SCROLLING */
// 'page top' link footer link functionality
$.fn.scrollToTop=function() {
	$(this).click(function() {
		$('html, body').animate({scrollTop:0},'fast');
		return false;
	});
}

// scroll to passed anchor.
// used in lead / vehicle detail quick links
function goToByScroll(id){
	$('html,body').animate({scrollTop: $("#"+id).offset().top},'fast');
}

/* FOCUS FIELD FUNCTION */

function focusInOut(selector) {
	$(selector).focus(function() {
		$(this).addClass('focused');
		if(!$(this).data('origText')) {
			$(this).data('origText',$(this).val());
			$(this).val('');
		} else {
			$(this).data('newText',$(this).val());
			if($(this).data('newText') == $(this).data('origText')) {
				$(this).val('');
			}
		}
	});
	$(selector).blur(function() {
		$(this).removeClass('focused');
		if(!$(this).val()) {
			$(this).val($(this).data('origText'));
		}
	});
}

function changeOpacity(element,opacity) {
	$(element).css('opacity',opacity);
}
