﻿$().ready(function(){


	setInterval("checkAnchor()", 300);
	//test();

$.ajax({
				type: "POST", 
				url: "CountryCode.php", 
				data: "action=eee",
				complete: function(data){

					countryCode = data.responseText;
					//alert(countryCode);
					$("#location").val($("option[id='" + countryCode + "']").val());
						
					}
				});	



		$('#location').change(function () {
          var str = "";
          $("#location option:selected").each(function () {
                str += $(this).text() + " ";
				countryCode = this.id;
				//alert(countryCode);
              });
		  
 
        }).change();
		
		$('#categories').change(function () {
          var str = "";
          $("#categories option:selected").each(function () {
                str += $(this).text() + " ";
				category = this.id;
				//alert(category);
              });
		  
 
        }).change();		


		



		


	
	
	// actions to be taken when the page is ready
	//contentWrapper.hide();
	//ebay_loading.hide();
	//contentWrapper.css("visibility","hidden");
	//ebay_loading.css("visibility","hidden");

	searchBoxQuery.val(searchBoxDefault);
	

	smartColumns($("ul.column"), $("ul.column li"), 190);		
	
	
	

	
	
	//on form submit event
	$("#searchform").submit(function(){
		window.location.href = "#searchProducts"; 
		contentWrapper.css("border","1px solid #d0ccc9");
		createCookie("first_query", searchBoxQuery.val(), 100);
		return doProductSearch(1, searchBoxQuery.val(), "productSearch", "");		
	});
	
	
	//Manage click events
	// pages.live("click",function(){
		// content.hide();
		// var classname = $(this).attr("class");
		// //Load content
		// if(classname == 'pg-normal')
		// {
			// var pageNum = this.id;
			// var pagesQuery = $("#pages_query").val();
			// updateSearchBox(pagesQuery);			
			// return doProductSearch(pageNum, pagesQuery, "productSearch", "");			
		// }
	// });	
	
	//Manage click events
	// $("#details_pages li").live("click",function(){
		// $("#mycarousel").hide();
		// var classname = $(this).attr("class");
		// //Load content
		// if(classname == 'pg-normal')
		// {
			// var pageNum = this.id;
			// var pagesQuery = $("#pages_query").val();
			// //alert(pagesQuery);			
			// return doEbayProductSearch(pageNum, pagesQuery, "ebayProductSearch");			
		// }
	// });		
	
	
	
	searchBoxQuery.focus(function(){  
		if($(this).attr("value") == searchBoxDefault) $(this).attr("value", ""); 
		$(this).css("border","1px solid #666");
		$(this).css("outline", "none");
	});
	
	
	searchBoxQuery.blur(function(){  
		if($(this).attr("value") == "") $(this).attr("value", searchBoxDefault); 
		$(this).css("border","1px solid #6885A2");
		$(this).css("outline", "none");
	});
	
 
	$(window).resize(function (){
		smartColumns($("ul.column"), $("ul.column li"), 190);		
	});
	
	
	// details.live("click",function(){
	// //alert("in details()");
		// content.hide();
		// return doCompareSearch(1, this.title, "compare", this.id);
		// //return doProductSearch(1, "", "seedetails", this.id);		
	// });
	
	





	
	
});

	
	var currentAnchor = null;


	//global vars
	var ITEMS_PER_PAGE = 24;
	var FADE_TIME = 2000;
	var COOKIE_LIFE_TIME = 3;	
	var searchBoxQuery = $("#inputField");
	var loading = $("#loading");
	var ebay_loading = $("#ebay_loading");
	var pages = $("#pages a");
	var paginationPlaceHolder = $("#pagination_place_holder");
	var detailsPaginationPlaceHolder = $("#details_pagination_place_holder");
	var searchBoxDefault = "Search ...";		
	var content = $("#content");
	var contentWrapper = $("#contentWrapper");
	var homeText = $("#home_text");
	var details = $(".details a");
	var footer = $("#footer");
	//var category = "DVD";
	//var category = "Blended";
	var category = "All";
	var countryCode = "US";


function checkAnchor(){

	var pageNum = 1;
	var anchorValue = "";
	//Check if it has changes
	if(currentAnchor != document.location.hash){
		currentAnchor = document.location.hash;

		//if there is not anchor, the loads the default section
		if(!currentAnchor)
		{
			//default - page = 1
			//pageNum = 1;
			window.location = "#home";
		}
		else
		{
			//get the page number after #
			anchorValue = currentAnchor.substring(1);
		}
		
		
		
		//Send the petition and display the result
		
		
		//var classname = $(this).attr("class"); //no this here
		//alert(classname);
		//Load content
		if(anchorValue.indexOf('searchEbayProducts/page') != -1)
		{
			pageNum = anchorValue.substring("searchEbayProducts/page/".length);
			
			//var pagesQuery = $("#pages_query").val();
			//var amazon_title_query = readCookie("amazon_title_query");
			var amazon_title_query_processed = $("#amazon_title_query_processed").val();

			//alert(amazon_title_query_processed);
			return doEbayProductSearch(pageNum, amazon_title_query_processed, "ebayProductSearch");
		}		
		else if(anchorValue.indexOf('searchProducts/page') != -1)
		{
			content.hide();
			pageNum = anchorValue.substring("searchProducts/page/".length);
			var user_query = readCookie("first_query");
			//var user_query = $("#user_query").val();
			//alert(user_query);
		
			updateSearchBox(user_query);			
			return doProductSearch(pageNum, user_query, "productSearch", "");			
		}
		else if(anchorValue.indexOf('compare') != -1)
		{
			var asin_title = anchorValue.substring('compare_'.length);
			var title = asin_title.substring(asin_title.indexOf('_')+1);
			var asin = asin_title.substring(0,asin_title.length - title.length - 1);
			//alert(title +"999" + asin);
			content.hide();
			//createCookie("amazon_title_query", title, 100);
			return doCompareSearch(1, title, "compare", asin);		
		}
		else if(anchorValue.indexOf('search') != -1)
		{
			content.hide();

			
			var first_query = readCookie("first_query");

			
			updateSearchBox(first_query);			
			return doProductSearch(1, first_query, "productSearch", "");			
		}
		else if(anchorValue.indexOf('home') != -1)
		{
			contentWrapper.css("border","0px solid #d0ccc9");
			content.hide();
			homeText.show();
			paginationPlaceHolder.hide();			
			//home page
			//currentAnchor = null;
			//location.reload(); 
		}


	}
}




	// functions
	


	
	
	
	function showLoading(loading_var){ 
	 loading_var  
		 .css({visibility:"visible"})  
		 .css({opacity:"1"})  
		 .css({display:"block"})  
	 ;
	}
	
	//hide loading bar  
	function hideLoading(){  
		loading.hide();
		content.fadeIn(FADE_TIME); 
	} 
	

	function smartColumns(ulColumn, ulColumnLi, width){
		//var ulColumn = $("ul.column");
		//var ulColumnLi = $("ul.column li");
		ulColumn.css({ 'width' : "100%"});
		
		var colWrap = ulColumn.width();
		var colNum = Math.floor(colWrap / width);
		var colFixed = Math.floor(colWrap / colNum);		
		
		ulColumn.css({ 'width' : colWrap});
		ulColumnLi.css({ 'width' : colFixed});		
	}
	

	function createCookie(name,value,minutes){
		if (minutes){
			var date = new Date();
			date.setTime(date.getTime()+(minutes*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}
	

	function readCookie(name){
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) 
		{
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}
	

	function eraseCookie(name){
		createCookie(name,"",-1);
	}
	
	
	function doProductSearch(pagenumber, query, action, asin){
			//alert(category);
			query = query.replace("&", "%26");
			
			
			
	//$("#contentWrapper_place_holder").html="<div class=\"contentWrapper\" id=\"contentWrapper\"><div id=\"loading\"><img alt=\"Loading...\" src=\"images/ajax-loader.gif\" /></div><div id=\"content\></div><div id=\"ebay_loading\"><img alt=\"Loading...\" src=\images/ajax-loader.gif\" /></div><span id=\"details_pagination_place_holder\"></span></div>";			
			
			
			
			
			contentWrapper.show();
			homeText.hide();
			content.hide();
			paginationPlaceHolder.hide();
			detailsPaginationPlaceHolder.hide();
			ebay_loading.hide();
			showLoading(loading); 
			
			$.ajax({
				type: "POST", 
				url: "amazon.php", 
				data: "action=" + action + "&user_query=" + query + "&numresults=" + ITEMS_PER_PAGE + "&pagenumber=" + pagenumber + "&asin=" + asin + "&category=" + category,
				complete: function(data){
						loading.hide();
						content.html(data.responseText);
						content.show();
						smartColumns($("ul.column"), $("ul.column li"), 190);
						smartColumns($("#mycarousel ul"), $("#mycarousel ul li"), 90);
			
						var totalPages = $("#totalpages").val();
						maxpages = 400;
						if(category == "All")
						{
							maxpages = 5;
						}
						totalPages = Math.min(maxpages, totalPages);
						if(totalPages > 0 && action == "productSearch")
						{
							var pagesHtml = drawPages(parseInt( totalPages ), parseInt( pagenumber ), "pagination_div", "pages", "searchProducts/page/");
							paginationPlaceHolder.html(pagesHtml);
							paginationPlaceHolder.show();							
						}
						
						
						   $(".block").fadeTo(0, 0.85);
						   $(".block").hover(function(){
						   $(this).fadeTo("normal", 1.0); // This should set the opacity to 100% on hover
						   },function(){
						   $(this).fadeTo("fast", 0.85); // This should set the opacity back to 30% on mouseout
						   });						
						
						/*if(totalPages > 0 && action == "seedetails")
						{
							var pagesHtml = drawPages(parseInt( totalPages ), parseInt( pagenumber ), "details_pagination_div", "details_pages");
							detailsPaginationPlaceHolder.html(pagesHtml);
							detailsPaginationPlaceHolder.show();							
						}						
						

						$(".images_calousel img").click(function() {
							//alert($(this).attr("id"));
							//$("#ebay_details img").attr("src", $(this).attr("src"));
							return doEbayDetailsSearch(1, $(this).attr("id"), "ebaydetails", "");

						})*/

						
						//////////

						
					}
				});
		//we prevent the refresh of the page after submitting the form
		return false;
	}
	
	
	function doCompareSearch(pagenumber, full_amazon_title, action, asin){
			//alert(countryCode);
			
			full_amazon_title = full_amazon_title.replace("&", "%26");
			contentWrapper.show();
			homeText.hide();
			content.hide();
			paginationPlaceHolder.hide();
			detailsPaginationPlaceHolder.hide();
			showLoading(ebay_loading);
			var user_query = readCookie("first_query");
			//var user_query = $("#user_query").val();
			//alert(user_query);
			
			$.ajax({
				type: "POST", 
				url: "amazon.php", 
				data: "action=" + action + "&amazon_title_query=" + full_amazon_title + "&asin=" + asin + "&user_query=" + user_query + "&category=" + category + "&countryCode=" + countryCode,
				complete: function(data){
						ebay_loading.hide();
						content.html(data.responseText);
						content.show();
						smartColumns($("ul.column"), $("ul.column li"), 190);
						smartColumns($("#mycarousel ul"), $("#mycarousel ul li"), 90);
			
						var totalPages = $("#totalpages").val();
						var amazon_price = $("#amazon_price").val();
						createCookie("amazon_details_price", amazon_price, 100);

						if(totalPages > 0 && action == "compare")
						{
							var pagesHtml = drawPages(parseInt( totalPages ), parseInt( pagenumber ), "details_pagination_div", "details_pages", "searchEbayProducts/page/");
							detailsPaginationPlaceHolder.html(pagesHtml);
							detailsPaginationPlaceHolder.show();							
						}
						else
						{
							$("#ebay_details").html("No Ebay items found");
							$("#mycarousel").hide();
							$("#newline").hide();
						}
						
						
						   $(".block_calousel").fadeTo(0, 0.85); // This sets the opacity of the thumbs to fade down to 30% when the page loads
						   $(".block_calousel").hover(function(){
						   $(this).fadeTo("normal", 1.0); // This should set the opacity to 100% on hover
						   },function(){
						   $(this).fadeTo("fast", 0.85); // This should set the opacity back to 30% on mouseout
						   });						
						
						
						$(".images_calousel").click(function() {
							var id_shipprice = jQuery("img", this).attr("id");
							//alert(id_shipprice);
							//var id_shipprice = $(this).attr("id");
							var shipprice = id_shipprice.substring(id_shipprice.indexOf('_')+1);
							var id = id_shipprice.substring(0, id_shipprice.length - shipprice.length - 1);
							//alert(id+" " + shipprice);
							//$("#ebay_details img").attr("src", $(this).attr("src"));
							return doEbayDetailsSearch(1, id, "ebaydetails", "", shipprice);

						})

						
						//////////

						
					}
				});
		//we prevent the refresh of the page after submitting the form
		return false;
	}	
	
	//for ebay pagination clicks
	function doEbayProductSearch(pagenumber, query, action){
			
			query = query.replace("&", "%26");
			contentWrapper.show();
			homeText.hide();
			$("#mycarousel").hide();
			paginationPlaceHolder.hide();
			detailsPaginationPlaceHolder.hide();
			showLoading(ebay_loading); 
			var user_query = readCookie("first_query");
			//var user_query = $("#user_query").val();
			var amazon_details_price = readCookie("amazon_details_price");
			$.ajax({
				type: "POST", 
				url: "amazon.php", 
				data: "action=" + action + "&query=" + query + "&pagenumber=" + pagenumber + "&user_query=" + user_query + "&category=" + category + "&countryCode=" + countryCode + "&amazon_details_price=" + amazon_details_price,
				complete: function(data){
						ebay_loading.hide();
						$("#mycarousel").html(data.responseText);
						$("#mycarousel").show();
						smartColumns($("ul.column"), $("ul.column li"), 190);
						smartColumns($("#mycarousel ul"), $("#mycarousel ul li"), 90);
			
						var totalPages = $("#totalpages").val();
						
						if(totalPages > 0)
						{
							var pagesHtml = drawPages(parseInt( totalPages ), parseInt( pagenumber ), "details_pagination_div", "details_pages", "searchEbayProducts/page/");
							detailsPaginationPlaceHolder.html(pagesHtml);
							detailsPaginationPlaceHolder.show();							
						}
						else
						{
							$("#ebay_details").html("No Ebay items found");
							$("#mycarousel").hide();
							$("#newline").hide();
						}
						
						
						   $(".block_calousel").fadeTo(0, 0.85); // This sets the opacity of the thumbs to fade down to 30% when the page loads
						   $(".block_calousel").hover(function(){
						   $(this).fadeTo("normal", 1.0); // This should set the opacity to 100% on hover
						   },function(){
						   $(this).fadeTo("fast", 0.85); // This should set the opacity back to 30% on mouseout
						   });						
						
						$(".images_calousel img").click(function() {
							//alert($(this).attr("id"));
							//$("#ebay_details img").attr("src", $(this).attr("src"));
							var id_shipprice = $(this).attr("id");
							var shipprice = id_shipprice.substring(id_shipprice.indexOf('_')+1);
							var id = id_shipprice.substring(0, id_shipprice.length - shipprice.length - 1);							
							return doEbayDetailsSearch(1, id, "ebaydetails", "", shipprice);

						})

						
						//////////

						
					}
				});
		//we prevent the refresh of the page after submitting the form
		return false;
	}	
	
	
	function doEbayDetailsSearch(pagenumber, query, action, asin, shipprice){
			//alert(action);
			
			//$("#ebay_details").hide();
			$("#ebay_details").html("<div id=\"ebay_details_loading\"><img src=\"images/ajax-loader.gif\" /></div>");
			showLoading($("#ebay_details_loading"));
			
			$.ajax({
				type: "POST", 
				url: "amazon.php", 
				data: "action=" + action + "&itemId=" + query + "&numresults=" + ITEMS_PER_PAGE + "&pagenumber=" + pagenumber + "&asin=" + asin + "&shipprice=" + shipprice,
				complete: function(data){
						
						var ebay_details_data = data.responseText;
						//ebay_details_data += "<div id=\"ebay_details_loading\"><img alt=\"Loading...\" src=\"images/ajax-loader.gif\" /></div>";
						
						$("#ebay_details").html(ebay_details_data);
						$("#ebay_details_loading").hide();
						
						//////////

						
					}
				});
		//we prevent the refresh of the page after submitting the form
		return false;
	}	
	
	
	// function createPagesHtml(pagenumber, totalPages){			
		// var pagesHtml = '<div id="pagination_div"><ul id=\"pages\">';
		// for (pg=1; pg <= totalPages; pg++)
		// {
			// if(pg != pagenumber)
			// {
				// pagesHtml += "<li class=\"pg-normal\" id=" + pg +">"+ pg + "</li>";     
			// }
			// else			
			// {
				// pagesHtml += "<li class=\"pg-selected\" id=" + pg +">"+ pg + "</li>";						
			// }
		// }
		// pagesHtml += "</ul></div><span class=\"clear\"></span>";
		// return pagesHtml;
	// }
	
	/**
	 * Calculate start and end point of pagination links depending on 
	 * current_page and num_display_entries.
	 * @return {Array}
	 */
	function getInterval(totalPages, current_page)  {
		var num_display_entries = 6;
		var ne_half = Math.ceil(num_display_entries / 2);
		var upper_limit = totalPages - num_display_entries;
		var start = current_page>ne_half?Math.max(Math.min(current_page-ne_half, upper_limit), 0):0;
		var end = current_page>ne_half?Math.min(current_page+ne_half, totalPages):Math.min(num_display_entries, totalPages);
		return [start,end];
	}



	function drawPages(totalPages, current_page, pagination_div, pages, pages_name){
		if (totalPages == 1) return "";
		var num_edge_entries = 2;
		var interval = getInterval(totalPages, current_page);
		var pagesHtml = "<div id=\""+pages_name+"\"><ul id=\""+pages+"\">";
		
		// Generate "Previous"-Link
		if(current_page-1 > 0)
		{
			pagesHtml += "<a class=\"pg-normal\" href=\"#"+pages_name + (current_page-1) +"\">"+ "Prev" + "</a>";
		}
		
		// Generate starting points		
		if (interval[0] > 0 && num_edge_entries > 0)
		{
			var end = Math.min(num_edge_entries, interval[0]);
			for(var i=0; i<end; i++) 
			{
				pagesHtml += "<a class=\"pg-normal\" href=\"#"+pages_name + (i+1) +"\">"+ (i+1) + "</a>";				
			}
			if(num_edge_entries < interval[0])
			{
				pagesHtml += "<a class=\"pg-ellipse\">...</a>";
			}
		}
		// Generate interval links
		for(var i=interval[0]; i<interval[1]; i++) 
		{
			if(i+1 != current_page)
			{
				pagesHtml += "<a class=\"pg-normal\" href=\"#"+pages_name + (i+1) +"\">"+ (i+1) + "</a>";     
			}
			else			
			{
				pagesHtml += "<a class=\"pg-selected\" href=\"#"+pages_name + (i+1) +"\">"+ (i+1) + "</a>";						
			}
		}
		
		// Generate ending points
		if (interval[1] < totalPages && num_edge_entries > 0)
		{
			if(totalPages-num_edge_entries > interval[1])
			{
				pagesHtml += "<a class=\"pg-ellipse\">...</a>";
			}
			
			var begin = Math.max(totalPages-num_edge_entries, interval[1]);
			for(var i=begin; i<totalPages; i++) 
			{
				pagesHtml += "<a class=\"pg-normal\" href=\"#"+pages_name + (i+1) +"\">"+ (i+1) + "</a>";
			}		
		}
		
		// Generate "Next"-Link
		if(current_page-1 < totalPages-1)
		{
			pagesHtml += "<a class=\"pg-normal\" href=\"#"+pages_name + (current_page+1) +"\">"+ "Next" + "</a>";
		}
		
		pagesHtml += "</ul></div><span class=\"clear\"></span>";
		
		return pagesHtml;
	
	}
	

	//check if all fields are filled
	function checkForm(){
		if(searchBoxQuery.attr("value"))
			return true;
		else
			return false;
	}
	
	function updateSearchBox(query){
		if(query =="")
		{
			searchBoxQuery.val(searchBoxDefault);
		}
		else
		{
			searchBoxQuery.val(query);
		}
	}











