/*
	Office Location
	Latitude: 45.5172594
	Longitude: -122.6756256
*/
var api = "http://api.chandon.com";
var currentlocation,checkLocation,error,getrestaurantsurl,getlocationdata,getcuisines,productsdelimited,showCoupon,isLocationSet,totalRestaurants,more,totalRestaurants,latitude,longitude;
var loadcount = 0, total = 0;
var cuisines = "",calltoaction = "",distance = "",update = "",start = "";
var prev = "";
$(function () {

    // ?src=txt&filter=cocktail
    /*
    Chandon ?s=1
    Cocktail ?s=2
    Cheese ?s=3
    */

    $('#fullsite').click(function () {
        document.cookie = "RememberMe=True; path=/; domain=.chandon.com;";
    });

    if (getQuery('s') === '3') {
        $("#recipes").addClass('current');
        $("#mobile").mobile({
            history: '#/home',
            start: '#/recipes'
        });
    } else if (getQuery('s') === '2') {
        $("#cocktails").addClass('current');
        $("#mobile").mobile({
            history: '#/home',
            start: '#/cocktails'
        });
    } else if (getQuery('s') === '1') {
        $("#cocktails").addClass('current');
        $("#mobile").mobile({
            history: '#/home',
            start: '#/cocktails'
        });
    } else {
        $("#age-verification").addClass('current');
        $("#mobile").mobile({
            historyOffset: 1
        });
    }

    if (getQuery("l") === "signup") {
        $("#age-verification a").attr("href", "#club_chandon");
        $("#club_chandon .confirmation").attr("href", "#confirmation_coupon");
    }
    else if (getQuery("l") === "twoforone") {
        $("#age-verification a").attr("href", "#twoforone");
    }


    $("#home").bind("dynamic", function () {
        if (!$(this).data('loaded')) {
            findLocation();
            $("#home").data('loaded', true);
        }
    });

    function findLocation() {
        var checkLocation = setTimeout(function () {
            console.log("locaiton not set");
            locationNotSet();
        }, 15000);

        if (getQuery("distance")) {
            distance = getQuery("distance");
        };

        // Geo Location
        navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
        function foundLocation(position) {
            currentlocation = position.coords.latitude + "/" + position.coords.longitude;
            console.log("currentlocation: ", currentlocation)
            locationSet(currentlocation);
            /* Summer to Savor, Summer 2011 campign, checks if in California
            getState(currentlocation);
            */
        }

        function noLocation() {
            //	locationNotSet();
            currentlocation = "45.5172594/-122.6756256";
            locationSet("45.5172594/-122.6756256");
        }



    }

    function locationNotSet() {
        clearTimeout(checkLocation);
        $("#home .loading").fadeOut(0, function () {
            $("#home .promo li").html("<img src='/img/landing-photo.jpg' width='100%' alt='Photo'>");
            $("#home .navigation,.promo img").fadeIn(250);
        });
    }

    function locationSet(currentlocation) {
        isLocationSet = true;
        clearTimeout(checkLocation);
        $.getJSON(api + "/distance/location/" + currentlocation + "/?callback=?", function (data) {
            if (distance) {
                data = distance;
            }
            if (data < 100 && data > 5) {
                // if within 100 miles
                //console.log("You are winthin 100 miles of Chandon");
                $("#home .promo li a").attr("href", "/directions/index.html");
                $("#home .loading").fadeOut(0, function () {
                    $("#home .promo").addClass("text");
                    $("#home .promo li a").html("<span class='headline'>You’re Close&hellip;</span> <span class='body'>Need a little help finding us? We can help with that. </span> <span class='cta'>Go &rsaquo;</span>");
                    $("#home .navigation,.promo").fadeIn(250);
                });
            } else if (data < 5) {
                // if within 4 miles
                //console.log("You are at Chandon");
                $("#home .promo li a").attr("href", "#club_chandon");
                $("#home .loading").fadeOut(0, function () {
                    $("#home .promo").addClass("text");
                    $("#home .promo li a").html("<span class='headline'>Welcome to Domaine Chandon</span> <span class='body'>Join Club Chandon now and receive a mobile coupon for a free glass of bubbly in the Tasting Lounge.</span> <span class='cta'>Join Now &rsaquo;</span>");
                    $("#home .navigation,.promo img").fadeIn(250);
                });
                showCoupon = true;
                if ($.jCookie('couponCode') && $.jCookie('couponIssueDate')) {
                    $("#home .navigation").append("<li><a href='#confirmation_coupon'>Get Coupon</a>");
                }
                $("#club_chandon .navigation a").attr("href", "#confirmation_coupon");
            } else {
                // if out of range
                //console.log("You are out of range");
                $("#home .loading").fadeOut(0, function () {
                    $("#home .promo li").html("<img src='/img/landing-photo.jpg' width='100%' alt='Photo'>");
                    $("#home .navigation,.promo img").fadeIn(250);
                });
            }
        });
    }

    function getState(geo) {
        $.getJSON(api + '/location/geo/' + geo, function (data) {
            if (data.Region == 'CA' && getQuery('win') == 'true' || getQuery('state') == 'ca') {
                // Users referrer us chandon.com/win and is in CA
                $('<li/>', {
                    html: $('<a/>', {
                        href: '#ca_offer',
                        text: '2-for-1 wine tasting'
                    })
                }).insertBefore('#home .navigation li:first');

                $("#home .navigation,.promo").fadeIn(250);

            } else if (data.Region != 'CA') {
                // Users is not in CA
                $('<li/>', {
                    html: $('<a/>', {
                        href: '#summer_to_savor',
                        text: 'Enter Summer Sweepstakes'
                    })
                }).insertBefore('#home .navigation li:first');

                $("#home .navigation,.promo").fadeIn(250);
            } else {
                // Users is in CA and not refered from chandon.com/win

                $("#home .navigation,.promo").fadeIn(250);

            }
        });
    }

    // Summer to savor mobile ad campign
    /*
    if (getQuery('win') == 'true' && getQuery('ad') == 'true') {
    $('#age-verification a').attr('href','#summer_to_savor');
    }
    */


    /*
    Restaurant Locator
    */

    $("#restaurant .location_data .update").click(function () {
        $("#restaurant .location_data").fadeOut(100, function () {
            $("#restaurant .update_location").fadeIn(250);
        });
        return false;
    });

    $("#restaurant .update_location .update").click(function () {
        // removes left and right whitespace
        update = $("#restaurant #update_location").val().replace(/^\s+/, '').replace(/\s+$/, '');
        $("#restaurant .error").remove();
        $("#restaurant .pagination").fadeOut(200);
        $("#restaurant .results").fadeOut(250, function () {
            $("#restaurant .results").html("");
            $("#restaurant .loading").fadeIn(250);
            $(".restaurant_detail").remove();
            getRestaurants(update);
        });
        return false;
    });

    $("#filter select").bind("change", function () {
        //pagination
        $('.pagination').fadeOut(200);

        //clear paging cache
        loadcount = 0;
        total = 0;

        if ($("#filter option:selected").text() === "Filter by Cuisine") return false;

        if ($("#filter option:selected").text() === "All Cuisine") {
            getcuisines = "";
        } else {
            getcuisines = "/cuisine/" + escape($("#filter option:selected").text());
        }

        currentlocation = latitude + "/" + longitude;

        $("#restaurant .results").fadeOut(250, function () {
            $("#restaurant .results").html("");
            $("#restaurant .loading").fadeIn(250);
            $.getJSON(api + "/restaurants/location/" + currentlocation + getcuisines + "/?callback=?", function (data) {
                $(".restaurant_detail").remove();
                $.each(data, function (i, item) {
                    total = i;
                });
                displayRestaurants(data);
            });
        });
    });

    $("#restaurant").bind("dynamic", function () {
        if (!$(this).data('loaded')) {
            loadcount = 0;
            total = 0;
            getRestaurants();
            $('#restaurant .pagination .next').live('click', function () {
                $('#restaurant .pagination .next').html('<img src="/img/loading-small.gif" width="16" height="16" class="loading">');
                getRestaurants('update', 'more');
                return false;
            });
            $("#restaurant").data('loaded', true);
        }
    });

    $("#confirmation_coupon").bind("dynamic", function (e, info) {
        if (!$(this).data('loaded')) {
            if ($.jCookie('couponCode') && $.jCookie('couponIssueDate')) {
                $(".issue_date").text($.jCookie('couponIssueDate'));
                $(".unique_code").text($.jCookie('couponCode'));
            } else {
                var currentTime = new Date();
                var month = currentTime.getMonth() + 1;
                var day = currentTime.getDate();
                var year = currentTime.getFullYear();
                function randomCode(length) {
                    character = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
                    code = "";
                    for (var x = 0; x < length; x++) {
                        i = Math.floor(Math.random() * 62);
                        code += character.charAt(i);
                    }
                    return code;
                }
                var generatedCode = randomCode(20);
                $(".issue_date").text(month + "/" + day + "/" + year);
                $(".unique_code").text(generatedCode);
                $.jCookie('couponCode', generatedCode, 1, { path: "/" });
                $.jCookie('couponIssueDate', month + "/" + day + "/" + year, 1, { path: "/" });
            }
        }
    });

    /*
    Store Locator
    */

    $("#store .location_data .update").click(function () {
        $("#store .location_data").fadeOut(100, function () {
            $("#store .update_location").fadeIn(250);
        });
        return false;
    });

    $("#store .update_location .update").click(function () {
        // removes left and right whitespace
        update = $("#store #update_location").val().replace(/^\s+/, '').replace(/\s+$/, '');
        $("#store .error").remove();
        $("#store .pagination").fadeOut(200);
        $("#store .results").fadeOut(250, function () {
            $("#store .results").html("");
            $("#store .loading").fadeIn(250);
            $(".store_detail").remove();
            getStores(update);
        });
        return false;
    });

    $("#store").bind("dynamic", function () {
        if (!$(this).data('loaded')) {
            loadcount = 0;
            total = 0;
            getStores();
            $('#store .pagination .next').live('click', function () {
                $('#store .pagination .next').html('<img src="/img/loading-small.gif" width="16" height="16" class="loading">');
                getStores('update', 'more');
                return false;
            });
            $("#store").data('loaded', true);
        }
    });

    $("#club_chandon").bind("dynamic", function () {
        // Reset all values
        $('#sign_up label small').remove();
        $('#sign_up input').each(function () {
            $(this).val('');
        });
        $('#sign_up #state').each(function () {
            $('#state option:eq(0)').attr('selected', true);
        });
    });



    /*
    Club Chandon Signup
    */

    $('.club_sign_up').live('click', function () {
        var firstName = $('#first_name').val();
        var lastName = $('#last_name').val();
        var address = $('#address').val();
        var postalCode = $('#postal_code').val();
        var city = $('#city').val();
        var state = $('#state :selected').val();
        var email = $('#email_address').val();
        var month = $('#month').val();
        var day = $('#day').val();
        var year = $('#year').val();
        var password = $('#password').val();
        var news = $("#news:checked").length ? true : false;
        var offers = $("#offers:checked").length ? true : false;

        if (firstName && lastName && address && postalCode && city && state && email && month && day && year && password && isValidEmail(email)) {
            $.getJSON(api + '/mobile/ClubSignUp?firstName=' + firstName + '&lastName=' + lastName + '&address=' + address + '&city=' + city + '&state=' + state + '&postalCode=' + postalCode + '&emailAddress=' + email + '&month=' + month + '&day=' + day + '&year=' + year + '&password=' + password + '&news=' + news + '&offers=' + offers + '&callback=?',
			function (data) {
			    $('.confirmation').click();
			});
        } else {
            $('#sign_up label small').remove();
            $('#sign_up input.required').each(function () {
                if (!$(this).val()) {
                    $('label[for=' + $(this).attr('id') + ']').html($('label[for=' + $(this).attr('id') + ']').text() + ' <small>This field is required</small>');
                }
            });
            if (state == 'select') {
                $('label[for=state]').html('State <small>This field is required</small>');
            }
            if (!isValidEmail(email)) {
                $('label[for=email_address]').html('Email Address <small>This field is required</small>');
            }
        }

        return false;
    });

    var userId;

    $('#s2s_state').live('change', function () {
        if ($('#s2s_state option:selected').val() == 'CA') {
            $('.ca_offer').click();
        }
    });

    $('.sweeps_sign_up').live('click', function () {
        var firstName = $('#s2s_first_name').val();
        var lastName = $('#s2s_last_name').val();
        var address = $('#s2s_address').val();
        var postalCode = $('#s2s_postal_code').val();
        var city = $('#s2s_city').val();
        var state = $('#s2s_state :selected').val();
        var email = $('#s2s_email_address').val();
        var month = $('#s2s_month').val();
        var day = $('#s2s_day').val();
        var year = $('#s2s_year').val();
        var twitter_username = 'null';
        var password = $('#password').val();
        var news = $("#news:checked").length ? true : false;
        var offers = $("#offers:checked").length ? true : false;

        var checkAge = isLegalAge(day, month, year);

        if (firstName && lastName && address && postalCode && city && state && email && checkAge && isValidEmail(email)) {
            var data =
			firstName +
			'/' +
			lastName +
			'/' +
			address +
			'/' +
			'null' +
			'/' +
			city +
			'/' +
			state +
			'/' +
			postalCode +
			'/' +
			email +
			'/' +
			month + '-' + day + '-' + year +
			'/' +
			twitter_username +
			'/' +
			'facebook';

            $.getJSON(api + '/escape-registration/' + data + '?callback=?', function (data) {
                userId = data.UserId;
                $('.s2s_confirmation').click();
                /*
                Start of DoubleClick Floodlight Tag: Please do not remove
                Activity name of this tag: Chandon Contest Entry Mobile Confirmation Page
                URL of the webpage where the tag is expected to be placed: http://m.chandon.com/index.html?win=true&ad=true#/sweeps_sign_up
                This tag must be placed between the <body> and </body> tags, as close as possible to the opening tag.
                Creation Date: 04/14/2011
                */
                var axel = Math.random() + "";
                var a = axel * 10000000000000;
                $('<iframe src="http://fls.doubleclick.net/activityi;src=2486000;type=2011c341;cat=chand063;ord=' + a + '?" width="1" height="1" frameborder="0" style="display:none"></iframe>').appendTo('body');
            });

        } else {
            $('#s2s_sign_up label small').remove();
            $('#s2s_sign_up input.required').each(function () {
                if (!$(this).val()) {
                    $('label[for=' + $(this).attr('id') + ']').html($('label[for=' + $(this).attr('id') + ']').text() + ' <small>This field is required</small>');
                }
            });
            if (state == 'select') {
                $('label[for=state]').html('State <small>This field is required</small>');
            }
            if (!isValidEmail(email)) {
                $('label[for=email_address]').html('Email Address <small>This field is required</small>');
            }
        }

        return false;
    });


    $('#get_coupon').live('click', function () {
        $.getJSON(api + '/escape/coupon/email/' + $('#coupon_email_address').val() + '/?callback=?', function (data) {
            $('#offer_confirmation').click();
        });
        return false;
    });


    //	

    $('.s2s_club_sign_up').live('click', function () {
        var password = $('#s2s_club_password').val();
        var news = $('#s2s_club_news:checked') ? 'false' : 'true';
        var offers = $('#s2s_club_offers:checked') ? 'false' : 'true';

        if (password) {

            $.getJSON(api + '/escape-clubregistration/' + userId + '/' + password + '/' + 'true' + '/' + news + '/' + offers + '?callback=?', function (data) {

                $('.s2s_club_sign_up_confirmation').click();

            });

        } else {
            $('#s2s_club_sign_up label small').remove();
            $('#s2s_club_sign_up input.required').each(function () {
                if (!$(this).val()) {
                    $('label[for=' + $(this).attr('id') + ']').html($('label[for=' + $(this).attr('id') + ']').text() + ' <small>This field is required</small>');
                }
            });
        }

        return false;
    });

});  // end doc load

function isValidEmail(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

function getRestaurants(update,more) {
	if (more) {
		loadcount++;
		start = 'start=' + 25*loadcount;
	}
	
	if (isLocationSet || update) {
		if (!more) {
			$("#restaurant .loading").fadeIn(0);	
		}
		
		if (update && !more) {
			currentlocation = update;
		}
		
		if (update && !more) {
			error = setTimeout(function() {
				$("#restaurant .loading").fadeOut(100,function(){
					$("#restaurant .content").append("<h2 style='padding:100px 0 120px' class='error'>Couldn't find " + update + "</h2>");
				});
				clearTimeout(error);
				return false;
			},10000);
		}
		
		if (update && !more) {
			getrestaurantsurl = api + "/restaurants/place/" + update + "/?callback=?";
			getlocationdata = api + "/location/place/" + update + "/?callback=?";
		} else if (more) {
			getrestaurantsurl = api + "/restaurants/location/" + currentlocation + "/?" + start +"&callback=?";
		} else {
			getrestaurantsurl = api + "/restaurants/location/" + currentlocation + "/?callback=?";
			getlocationdata = api + "/location/geo/" + currentlocation + "/?callback=?";	
		}
		$.getJSON(getlocationdata, function(data) {
			if (!more) {
				$("#restaurant .count").html(data.RestaurantCount);
				$("#restaurant .location").html(data.City + ", " + data.Region);
				latitude = data.Latitude;
				longitude = data.Longitude;
				$("#filter select").html("<option>Filter by Cuisine</option><option id='all_cuisine'>All Cuisine</option>");
				$.each(data.Cuisines,function(i, item) {
					$("<option>").attr("value", item.Id).text(item.Name).appendTo("#filter select");
				});
			}
			
			if (!update) {
				$("#restaurant .location_data").fadeIn(200);
			} else {
				$("#restaurant .loading").fadeOut(0);
			}
		});	

		$.getJSON(getrestaurantsurl, function(data) {	
			displayRestaurants(data,update);
			$("#filter").fadeIn(200);
	    });
	} else {
		$("#restaurant .loading").fadeOut(100,function(){
			$('#restaurant .update_location').fadeIn(250);
		});	
	}
	
	
}

function displayRestaurants(data) {
	if (isLocationSet || update) {
		$("#restaurant .loading").fadeOut(0);
		$.each(data, function(i, item) {
			clearTimeout(error);
			if (item.ReserveOnline) {
				calltoaction = "<ul class=\"button\">" +
					"<li><a href="+item.OpenTableUrl+" target=\"_blank\">Make a reservation</a></li>" +
				"</ul>";
			}
		
			if (item.Url) {
				calltoaction = "<ul class=\"button\">" +
					"<li><a href="+item.Url+" target=\"_blank\">View website</a></li>" +
				"</ul>";
			}
		
			if (item.Url && item.ReserveOnline) {
				calltoaction = "<ul class=\"button\">" +
					"<li><a href="+item.Url+" target=\"_blank\">View website</a></li>" +
					"<li><a href="+item.OpenTableUrl+" target=\"_blank\">Make a reservation</a></li>" +
				"</ul>";
			}

			if (item.CuisinesDelimiteds) {
				cuisines = "<ul>" +
					"<li>"+item.CuisinesDelimited+"</li>" +
				"</ul>";
			}

			if (item.CuisinesDelimited) {
				cuisinesDelimited = item.CuisinesDelimited;
			}
			
			// fix for mal formated phone numbers
			var phone = item.Phone.replace(') ','-').replace('(','');
			
			total = i;
			$("#restaurant ul.results").append("<li id='id_"+item.Id+"'>" +
				"	<a href='#restaurant_"+item.Id+"' class='restaurant'>" +
				"	<h3>" + item.Name + "</h3>" +
				"	<p>" + cuisinesDelimited +"</p>" +
				"	</a>" +
				"</li>");
			$("#mobile").append("<div id=\"restaurant_"+item.Id+"\" class=\"restaurant_detail\">" +
				"<div class=\"content\">" +
				"	<h2>"+item.Name+"</h2>" +
				"<div class=\"info\">" +
				"	<p><a href=\"http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q="+item.Address+"+"+item.City+",+"+item.State+"\" target=\"_blank\">" + item.Address + "<br>" + item.City + ", " + item.State + "</a></p>" +
				"	<p><a href=tel:"+ phone +" target=\"_blank\">"+item.Phone+"</a></p>" +
					cuisines +
				"</div>" +
				"</div>" +
				calltoaction +
				"</div>");
			
			
		});	
			if (update) {
				$("#restaurant .update_location").fadeOut(100,function(){
					$("#restaurant .location_data").fadeIn(250);
				});
			}
			$("#restaurant .results").fadeIn(250,function(){
				if (total < 24) {
					$('#restaurant .pagination').fadeOut(250);
					//clear paging cache
					loadcount = 0;
				} else {
					$('#restaurant .pagination .next').text('Load More');
					$('#restaurant .pagination').fadeIn(250);
				}	
			});
			$('.error').fadeOut(0);
	}
}

function getStores(update,more) {
	if (more) {
		loadcount++;
		start = 'start=' + 25*loadcount;
	}
	if (isLocationSet || update) {
		if (!more) {
			$("#store .loading").fadeIn(0);	
		}
		
		if (update && !more) {
			currentlocation = update;
		}
	
		if (update && !more) {
			getlocationdata = api + "/location/place/" + update + "/?callback=?";
		} else {
			getlocationdata = api + "/location/geo/" + currentlocation + "/?callback=?";
		}
	
		$.getJSON(getlocationdata, function(data) {
			$("#store .count").html(data.StoreCount);
			$("#store .location").html(data.City + ", " + data.Region);
			if (!update) {
				$("#store .location_data").fadeIn(200);
			}
		});
	
		if (update) {
			error = setTimeout(function() {
				$("#store .loading").fadeOut(100,function(){
					$("#store .content").append("<h2 style='padding:100px 0 120px' class='error'>Couldn't find " + update + "</h2>");
				});
				clearTimeout(error);
				return false;
			},10000);
		}
		
		if (more) {
			$.getJSON(api+"/stores/location/"+currentlocation+"/?" + start + "&callback=?", function(data) {
				displayStores(data,update);
		    });
		} else {
			$.getJSON(api+"/stores/location/"+currentlocation+"/?callback=?", function(data) {
				displayStores(data,update);
		    });
		}

	
	} else {
		$("#store .loading").fadeOut(100,function(){
			$('#store .update_location').fadeIn(250);
		});	
	}
}

function displayStores(data) {
	if (isLocationSet || update) {
		$("#store .loading").fadeOut(0);
		$.each(data, function(i,item) {
			clearTimeout(error);
			// compares & remove duplicates
/*
			if (i > 1) {
				ii = (i > 0) ? i - 1 : i;
				previous = data[ii].Name + "," + data[ii].Address;
				next = item.Name + "," + item.Address;
			} else {
				previous = 0;
				next = 1;
			}*/


				total = i;
				$("#store .results").append("<li id='id_"+item.Id+"'>" +
				"<a href='#store_"  + item.Id + "'>" +
				"<h3>" + item.Name + "</h3>" +
				"<p>" + item.Distance + " miles</p>" +
				"</a>" +
				"</li>");
				if (item.ProductsDelimited) {
					productsdelimited = "<h3>Products:</h3><p>" + item.ProductsDelimited + "</p>";
				} else {
					productsdelimited = "";
				}
				$("#mobile").append("<div id=\"store_"+item.Id+"\" class=\"store_detail\">" +
				"<div class=\"content\">" +
				"	<h2>"+item.Name+"</h2>" +
				"<div class=\"info\">" +
				"	<p><a href=\"http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q="+item.Address+"+"+item.City+",+"+item.State+"\" target=\"_blank\">"+item.Address+"<br>"+item.City+", "+item.State+"</a></p>" +
				"</div>" +
				productsdelimited +
				"</div>" +
				"</div>");
		
		});
		if (update) {
			$("#store .update_location").fadeOut(100,function(){
				$("#store .location_data").fadeIn(250);
			});
		}
		$("#store .results").fadeIn(250,function(){
			console.log("total: " + total);
			if (total < 24) {
				$('#store .pagination').fadeOut(250);
				//clear paging cache
				loadcount = 0;
			} else {
				$('#store .pagination .next').text('Load More');
				$('#store .pagination').fadeIn(250);
			}
		});
	}
}

function getQuery(obj) { 
	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] == obj) { 
			return pair[1]; 
		} 
	} 
}

