var page = 1; // global for other functions
var search_term;

$(document).ready(function() {

    $('#home_overlay').hide();

    setTimeout(function(){
        $('#home_overlay').fadeIn();
    }, 3000);

    $('#home_overlay .close').click(function(){
        $('#home_overlay').hide();            
    });

    $('#home_feature_left_list').hide();
    $('#home_feature_left').hide()
    $('#home_feature_left').fadeIn('slow');

    $('#home_overlay a.close').click(function(){
        $('#home_overlay').hide();
        return false;
    })

	$("#search").focus(function() {
		var val = $(this).val();
		if(val == "eg: Bookcase") {
			 $(this).val("");
		}
	});
	$("#search").blur(function() {
		var val = $(this).val();
		if(val == "") {
			 $(this).val("eg: Bookcase");
		}
	});

    $('#searchform').submit(function(){
        if($('#search_page').length > 0 )
        {
            var term = $('#search').attr('value');
            if(term != undefined && term != search_term)
            {
                $('#search_results').html('<img src="/site_media/images/ajax-loader.gif" alt="loading" id="ajaxloader" />');
                search_term = term;
                // do ajax search
                $.ajax({
                    url:'/search/',
                    type:'POST',
                    data:{search : $('#search').attr('value')},
                    success:function(msg){
                        $('#search_results').html(msg); 
                    }
                })
            }
            return false;
        }
        else
        {
            return true;
        }
    })
	
	$(".collectionFeature").hover(
		function () {
			$(this).css({backgroundPosition: "0 0", cursor: "pointer"});
		},
		function () {
			$(this).css("background-position","-358px 0")
		}
	);

	$(".collectionFeature").click(function() {
		window.location =  $("a",this).attr("href").toString();
		return false;
	});
	
	
	
	$("#sectionHomepage li").click(function() {
		var link 	= $("h2 a",this).attr("href").toString();	
		window.location = link;					
	});
	
	$("#sectionHomepage li").hover(
		function() {
			$("h2 a",this).css("color","#a9031b");
		},
		function() {
			$("h2 a",this).css("color","#8E7052")
		}		
	)
	
	$("#homeLogo").hide().fadeIn(2000);


    $('#stockist_form').submit(function(){
        var pcode = $('#id_postcode').val().replace(' ' ,'');
        var rad = $('#id_radius').val();
        var max = $('#id_max').val();
        Stockist.load({postcode:pcode, radius:rad, max:max});
        return false;
    });

    $('#id_postcode').focus(function(){
        $('#id_postcode').val('');
    })

    Product.init();
	
});


var Stockist = {
    load:function(obj) {
        var postcode = obj.postcode || '';
        var max = obj.max || 0;
        var radius = obj.radius || $('#id_radius').val();
        if(postcode != '')
        { 
            $.ajax({
                type:"POST",
                url:'/stockists/',
                data:{postcode:postcode, radius:radius, max:max},
                success:function(msg){
                    $('#results').html(msg);     
                }
            })
        }
        return false;
    }
}

function log(msg) {
    try {
        console.log(msg);
    } catch(e) {}
}

var currentProduct;
var ProductCache = {}
var currentPage;
var Product = {
    init:function()
    {
        Product.init_products();

        try{
            currentPage = $('.pagination a.sel')[0].href.match(/page(\d+)/)[1];
        } catch(e) {}


        $('.pagination .next_page').unbind('click').click(function(){
            Product.nextPage();
            return false;
        })
        $('.pagination .prev_page').unbind('click').click(function(){
            Product.prevPage();
            return false;
        })
        $('.pagination .page').unbind('click').click(function(){
            var p = parseInt($(this).html()); 
            Product.loadPage(p);
            return false;
        })
        try{
            $(open_product).click();
            open_product = null;
        } catch(e) {}
    },
    init_products:function()
    {
        $(".gridList li").hover(
            function() {
                $(this).css("cursor","pointer")
                $(".info",this).show();
            }
            ,
            function() {
                $(".info",this).hide();
            }
        );
        $("#resultsList li").unbind('click').click(function() {
            Product.current(this);
            return false;
        });
    },
    init_pagination:function()
    {
        var page_on = $('.page').removeClass('sel').get(currentPage-1)
        $(page_on).addClass('sel');
    },
    setMask:function()
    {
        var h = $("#resultsHolder").height();   // get height for mask 
        $("#mask").css("height",(h+10)+"px");
    },
    load:function(url)
    {
       //log("load called with: " + url);
       var h = $("#resultsHolder").height();   // get height for mask 

       if($.browser.msie && $.browser.version <= "6.0") { 
           $("#mask").css("height",(h+10)+"px").show();
           $("#viewer").show();
       } else {
               $("#mask").css("height",(h+10)+"px").fadeIn(300,function() {
                   $("#viewer").show();
               })
       }
        // Check cache and do ajax
        //if(!ProductCache[url])
        //{
            $("#viewerContent").html(
                '<img src="/site_media/images/ajax-loader.gif" alt="loading" id="ajaxloader" />'
            );	
            $.ajax({
               type: "POST",
               url:url+"?j=1",
               cache:false,
               success: function(msg){
                   $("#ajaxloader").fadeOut(400, function() {
                       $("#viewerContent").html(msg);
                       // Cache the result
                       //ProductCache[url] = msg;
                   })	   			
               },
               error: function(msg){
                    alert('error' + msg);
               }
            }); 
        //}
        //else
        //{
            // Serve from cache
        //    $("#ajaxloader").fadeOut(400, function() {
        //        $("#viewerContent").html(ProductCache[url]);
        //    })	   			
        //}
    },
    current:function(obj)
    {
        var curr = $(obj);
        var last = $('#products li:last');
        var first = $('#products li:first');
        var url = curr.find('a').attr('href');
        var this_page = url.match(/page(\d+)/)[1];
        
        Product.load(url)
    },
    next:function(obj)
    {
        log('next called');
        var url = obj ? $(obj).attr('href') : $('#next')[0].attr('href')
        if(url != '#' && url != undefined)
        {
            log('next url ok:' + url);
            Product.load(url) 
            var p = parseInt(url.match(/page(\d+)/)[1])
            if(p != currentPage)
            {
                Product.loadPage(p);
                $('#page_number').html(p);
                $('#page_number_bottom').html(p);
                currentPage = p;
                Product.init_pagination();
            } 
            
        }
        else
        {
            // last product
        } 
        return false;

    },
    prev:function(obj)
    {
        var url = obj ? $(obj).attr('href') : $('#prev')[0].attr('href');
        if(url != '#' && url != undefined)
        {
            log("prev url ok:" + url);
            Product.load(url) 
            var p = parseInt(url.match(/page(\d+)/)[1])
            log(currentPage + " " + p);
            if(p != currentPage)
            {
                Product.loadPage(p);
            } 
        }
        else
        {
            // last product
        }
        return false;
    },
    loadPage:function(p)
    {
        var p = parseInt(p);
        var max = $('#pagination_top a.page').length; 
        log('load page called' + p + " max is " + max);
        
        if( p >= 1 && p <= max ) 
        {

            $("#products").html(
                '<img src="/site_media/images/ajax-loader.gif" alt="loading" id="ajaxloader" />'
            );	
            var url = collection_base + "page" + p + "/";
            $.ajax({
               type: "POST",
               url:url+"?j=1",
               success:function(msg){
                        $('#products').html(msg);     
                        Product.init_products();
                        Product.setMask();
                        $('#page_number').html(p);
                        $('#page_number_bottom').html(p);
                        currentPage = p;
                        Product.init_pagination();
               }	   			
            })
        }
        return false;
    },
    nextPage:function()
    {
        Product.loadPage(parseInt(currentPage)+1)
        log('next page');         
    },
    prevPage:function()
    {
        log('prev page');
        Product.loadPage(parseInt(currentPage)-1)
    } 
}


/* Results List clicks */
function fnProductClick(obj, currIndex) {
	var h = $("#resultsHolder").height();	// get height for mask	
	page =  Math.ceil(currIndex/12) // what page are we on?	

	//populateViewer(currIndex); // Add comtent	
    Product.load(obj)

	if($.browser.msie && $.browser.version <= "6.0") { // fadeIn breaks ie pngfix so no animation
		$("#mask").css("height",(h+10)+"px").show();
		$("#viewer").show();
	} else {
		$("#mask").css("height",(h+10)+"px").fadeIn(300,function() {
			$("#viewer").show();
		})
	}
}


/*  Close Viewer */
function fnCloseViewer() {
	$("#viewer").hide();
	$("#mask").hide();	
}

/*  Poplate the viewer */
function populateList (pID) {
	
	// Set new page
	page = pID;
	
	// Update pagination
	$(".pagination h2 span").text(pID);
	
	// Do Ajax
	$("#resultsList ol").html('<li><img src="/site_media/images/ajax-loader.gif" alt="loading..."  /></li>');	
	$.ajax({
	   type: "GET",
	   url: "../" + pID,
	   success: function(msg){
			$("#resultsList ol").html(msg);	
			$("#resultsList li").hover(
			function() {
				$(".info",this).show();
			},
			function() {
				$(".info",this).hide();
			});
			$("#resultsList li").click(function() {
				var currIndex 	= $(this).attr("id").toString().split("result-")[1]; // product ID		
				fnProductClick(currIndex);					
			});		   			
	   }
	 });
}


/*  Poplate the viewer */
function populateViewer (index) {
	
	index = parseInt(index)
        
	// First, check this ID is in this page, if not, repopulate results list

    var last = $('#products li:last');
    var first = $('#products li:first');

    log('first: ' + first.attr('id'))
    log('last: ' + last.attr('id'))

	// Do Ajax
	$("#viewerContent").html('<img src="/site_media/images/ajax-loader.gif" alt="loading" id="ajaxloader" />');	
	$.ajax({
	   type: "GET",
	   url: "/product/" + index,
	   success: function(msg){
		$("#ajaxloader").fadeOut(400, function() {
			$("#viewerContent").html(msg);
		})	   			
	   }
	 }); 

}

function next() {
	populateViewer($("#next").attr("rel"))
}
function prev() {
	populateViewer($("#prev").attr("rel"))
}
