// JavaScript Document
jQuery.noConflict();

jQuery(document).ready(function(){
	init();
	if(jQuery('body.shop').length>0) initProductSection();
	if(jQuery('body.home').length>0) initHome();
	if(jQuery('.productSmall').length>0) initCustomSort();
})

var catalog = [];
var currentPage = 1;
var productsPerPage = 9;
var sortOrder = "weighting";
function initCustomSort(){
	var counter = 1;
	jQuery('.productSmall td').each(function(){
		// store all products in sortable array
		var product = jQuery(this);
		var addcartbutton = product.find('div.add-cart').html();
		var productname = product.find('h4').text();
		var productcode = product.find('div.product-code').text();
		var productimage = product.find('div.image img').attr('src');
		var producturl = product.find('div.image a').attr('href');
		var srtprice = product.find('div.product-price').text();
		var sortprice = srtprice.substring(srtprice.indexOf(' ')+2).replace(',','');
		var displayprice = product.find('div.product-price').html();
		
		if(product.find('h4').length>0) catalog.push({weighting:counter,name:productname,price:parseInt(sortprice),displayprice:displayprice,addcart:addcartbutton,code:productcode,image:productimage,url:producturl});
		counter ++;
	});
	
	//jQuery('table.productTable').remove();
	
	// page to view
	if("pg" in urlParams) currentPage = Number(urlParams['pg']);
	// sort order
	if("sort" in urlParams) sortOrder = urlParams['sort'];
	
	// Bind onchange trigger
	jQuery('.catalog-sort').change(function(){
		customSortOrder(jQuery(this).val());
	});
	// Hide drop down when no products available
	if(catalog.length==0) jQuery('.catalog-sort').hide();
	// change the selected drop down
	jQuery('.catalog-sort option[value=' + sortOrder + ']').attr('selected', 'selected');
	// trigger the intial redraw
	customSortOrder(sortOrder);
	//jQuery('table.productTable').css('display','none');
}

var sortby = function(field, reverse, primer){
   reverse = (reverse) ? -1 : 1;
   return function(a,b){
       a = a[field];
       b = b[field];

       if (typeof(primer) != 'undefined'){
           a = primer(a);
           b = primer(b);
       }
       if (a<b) return reverse * -1;
       if (a>b) return reverse * 1;
       return 0;
   }
}


function customSortOrder(key){
	var dir = (key.toUpperCase().indexOf('DESC')>-1)? true:false;
	var attribute = key.split('-')[0];
	catalog.sort(sortby(attribute, dir));
	sortOrder = key;
	// redraw catalog
	redrawCatalog();
}

function redrawCatalog(){
	jQuery('#catalog').empty();
	var products = catalog.length;
	var rangeMin = 0;
	var rangeMax = products;
	if(currentPage > 0){
		rangeMin = (currentPage -1)*productsPerPage;
		rangeMax = rangeMin + productsPerPage;
	}
	for(i=0;i<products;i++){
		if(i >= rangeMin && i < rangeMax){
			jQuery('#catalog').append(createProduct(catalog,i));
		}
	}
	if(products > productsPerPage){
		createPagination();
	}
} 

function createPagination(){
		var pages = Math.ceil(catalog.length/productsPerPage);
		var pagination = jQuery('<span class="pagination"></span>');
		//var sortorder = jQuery('select[name=catalog-sort]').val();
		//prev
		if(currentPage>1) pagination.append(jQuery('<a href="?pg='+ (currentPage-1) +'&sort='+sortOrder+'" class="prev">&lt;</a>'));
		// pages
		for(j=1;j<=pages;j++){
			var selected = '';
			if(currentPage==j){ selected = 'class="selected"';}
			pagination.append(jQuery('<a href="?pg='+ j +'&sort='+sortOrder+'" '+selected+'>' + j + '</a>'));
		}
		// next
		if(currentPage<pages) pagination.append(jQuery('<a href="?pg='+ (currentPage+1) +'&sort='+sortOrder+'" class="next">&gt;</a>'));
		// view all
		pagination.append(jQuery('<a href="?pg=-1&sort='+sortOrder+'" class="viewall">View All</a>'));
		jQuery('.nav-catalog-pagination').empty().append(pagination);
}

function createProduct(catarray,catindex){
	var productitem = jQuery('<div class="product-item" />');
	var wrapper = jQuery('<div class="shop-product-small clear" />');
	var image = jQuery('<div class="image"><a href="' + catarray[catindex].url + '"><img border="0"  title="' +  catarray[catindex].name + '" src="' + catarray[catindex].image + '" alt="' + catarray[catindex].name + '" src="' + catarray[catindex].image + '" id="catsproduct_913622"></a></div>');
	var content = jQuery('<div class="sleeve" />');
	var description = jQuery('<div class="product-description">' + catarray[catindex].code + '</div>');
	var name = jQuery('<h4 class="product-name"><a href="' + catarray[catindex].url + '">' + catarray[catindex].name + '</a></h4>');
	var price = jQuery('<div class="product-price">' + catarray[catindex].displayprice + '</div>');	
	var addcart = jQuery('<div class="product-add">' + catarray[catindex].addcart + '</div>');
	content.append(name).append(description).append(price).append(addcart);
	wrapper.append(image).append(content);
	productitem.append(wrapper);
	return productitem;
}

function debugCatalog(key){
	var output="";
	for(var i=0;i<catalog.length; i++){
		output += catalog[i][key] + ", ";
	}
	return output;
}

function initHome(){

}

function initProductSection(){

}

function init(){
	// Catalog main page
	if(jQuery('.productSmall').length>0){
		jQuery('body').addClass('shop-catalog');
	}
	
	// Product main page
	if(jQuery('.productLarge').length>0){
		jQuery('body').addClass('shop-product');
	}
}

var urlParams = {};
(function () {
    var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&;=]+)=?([^&;]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

    while (e = r.exec(q))
       urlParams[d(e[1])] = d(e[2]);
})();

var currentURL;
function setSubnavSelected(url){
	var currentEl = document.getElementById('subnav_' + urlParams['CatalogueID']);
	if(currentEl) currentEl.className = "selected";
	currentURL = url;
}

// checks if attribute label exists 
function checkAttributes(name){
	var att = document.getElementById('product-attributes');
	var searchindex = att.innerHTML.toString().toLowerCase().indexOf('>' + name.toLowerCase() + '<');
	if(searchindex > -1){
		return true;
	}else{
		return false;
		
	}
}




var popwin;
function openWindow(theURL,width,height,winfeatures,winname) {   
	var x = 10; 
	var y = 10;
	if(winfeatures==undefined){
		winfeatures = '';
	}
	if(winname==undefined){
		winname = '';
	}
	if(width!=undefined){
		x=(screen)?(screen.availWidth - width)/2:(640 - width)/2;
		winfeatures += ',width='+width;
	}
	if(height!=undefined){
		y=(screen)?(screen.availHeight - height)/2:(480 - height)/2;
		winfeatures += ',height='+height;
	}

	popwin = window.open(theURL,winname,'screenX='+x+',screenY='+y+',top='+y+',left='+x+',' + winfeatures);
	if(popwin.name==winname) popwin.focus();
}

// override draw product function so that we can trigger a custom event when new product is selected
function DrawProduct(b,j,g,d,a){var h=document.getElementById("Grouping_"+j);var c;var f=true;var i=h;while(f){i=i.parentNode;if(i.id){if(i.id.indexOf("catProdTd_")!=-1){c=i.id.substring(10);f=false}}}var e=CMS.CatalogueRetrieve.ServerSideDrawProduct(b,g,a,d);i.innerHTML=e.value;ProcessJS(i);if(e.value.indexOf("lightbox")!=-1){initLightbox()}
 customProductHandler(b,j,g,e);
}

function customProductHandler(catalogid,productid,value,html){
	if(html.value.indexOf("Material: 9ct Gold")>-1){
		alert("Please be aware due to the bespoke nature of a 9ct Gold piece the delivery timeframe for this product is two-three weeks.");
	}
}
