var PAGE_SIZE = 90;

function renderProducts(count, currentPage, currentSort, products, productImagePath, thisUri, noProductsFound, pages, sorting, category, price, color) {
    var res = '';

    res += '<div style="height:361px;padding:12px;">';
    var i = 15;

    if (products.length > 0) {
        res += '<table cellpadding="0" cellspacing="0" border="0">';

	    for (var n = 0; n < products.length; n++) {
	        var entity = products[n];

	        if (i % 15 == 0) {
	            res += '<tr>';
	        }

	        res += '<td style="padding:4px;">';
	        
	        res += '<div style="position:relative;width:52px;height:52px;">';
	        res += '<img width="52" height="52" onclick="openProductPopup(\'' + entity.uid + '\');" onmouseover="ZoomImage(this);Tip(\'' + entity.variantName + '\');" onmouseout="UnzoomImage(this);UnTip();" src="' + productImagePath + '&width=62&height=62&itemId=' + entity.uid + '" alt="" style="display:block;position:absolute;top:0;left:0;">';
	        res += '</div>';

	        res += '</td>';

	        if (i % 15 == 14) {
	            res += '</tr>';
	        }
	        i++;
	    }

/**/

        var intRest = i%15;
        for (var j = intRest; j < 15; j++) {
            res += '<td></td>';
        }
        if (i != 15) {
            res += '</tr>';
        }

        res += '</table>';

    } else {
        res += '<div style="width: 100%; top:50%; position:relative; text-align: center; vertical-align: middle"><strong>' + noProductsFound + '</strong></div>';
    }

    res += '</div>';

    res += '<div style="padding:0 16px 0 16px;height:15px;">';
    res += '<table cellpadding="0" cellspacing="0" border="0" width="100%">';
    res += '<tr>';
    res += '<td style="width:50%;" valign="top">';
    if (count > PAGE_SIZE) {
    	res += '<span class="assortment_heading">' + pages + '</span> ';
    	for (var j = 0; j < Math.ceil(count / PAGE_SIZE); j++) {
			if (j == currentPage) {
			    res += '<a href="javascript:ShowProductList(' + j + ');" class="paging_selected">' + (j + 1) + '</a> ';
			} else {
				res += '<a href="javascript:ShowProductList(' + j + ');" class="paging">' + (j + 1) + '</a> ';
			}
    	}
    }
    res += '</td>';

    res += '<td style="width:50%;" valign="top" align="center">';
    res += '<div id="sort_block">';
    res += '<span class="assortment_heading">' + sorting + '</span>&nbsp;&nbsp;&nbsp; ';
    res += '<a href="javascript:Sorting(\'category\');" class="' + ((currentSort == 'category') ? 'sorting_selected' : 'sorting') + '">' + category + '</a>&nbsp;&nbsp;&nbsp; ';
    res += '<a href="javascript:Sorting(\'price\');" class="' + ((currentSort == 'price') ? 'sorting_selected' : 'sorting') + '">' + price + '</a>&nbsp;&nbsp;&nbsp; ';
    res += '<a href="javascript:Sorting(\'color\');" class="' + ((currentSort == 'color') ? 'sorting_selected' : 'sorting') + '">' + color + '</a> ';
    res += '</div>';
    res += '</td>';
    res += '</tr>';
    res += '</table>';
    res += '</div>';

    return res;
}

function loadProducts(url, locale, productImagePath, thisUri, noProductsFound, pages, sorting, category, price, color) {
	var inpPage = document.getElementById("inpPage").value;
	var inpSorting = document.getElementById("inpSorting").value;
	var inpColor = document.getElementById("inpColor").value;

	var inpPriceArr = document.form1.inpPrice;
	var inpPrice = '';
	if (inpPriceArr) {
		var l = inpPriceArr.length;
		if (l == undefined && inpPriceArr.checked) inpPrice = inpPriceArr.value;
		for (var i = 0; i < l; i++) {
			if (inpPriceArr[i].checked) {
				inpPrice = inpPriceArr[i].value;
			}
		}
	}

	var inpCategoryArr = document.form1.inpCategory;
	var inpCategory = new Array();
	if (inpCategoryArr) {
		var l = inpCategoryArr.length;
		if (l == undefined && inpCategoryArr.checked) inpCategory[0] = inpCategoryArr.value;
		var j = 0;
		for (var i = 0; i < l; i++) {
			if (inpCategoryArr[i].checked) {
				inpCategory[j] = inpCategoryArr[i].value;
				j++;
			}
		}
	}

    $.ajax({
        type: 'GET',
        url: url,
        data: {'cmd': 'show_products', 'locale': locale, 'action': 'filter', 'inpCategory': inpCategory, 'inpPage': inpPage, 'inpSorting': inpSorting, 'inpColor': inpColor, 'inpPrice': inpPrice},
        success: function(data) {
            if (data.status == 'success') {
                document.getElementById("productPart").innerHTML = renderProducts(data.count, data.currentPage, data.currentSort, data.products, productImagePath, thisUri, noProductsFound, pages, sorting, category, price, color);
            } else if (data.status == 'error') {
                for (var l = 0; l < data.errors.length; l++) {
                    var e = data.errors[l];
                    alert('ERROR: ' + e.name + '\n\n' + e.stacktrace);
                }
            } else {
                alert('Undefined status: ' + data.status);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("error. textStatus" + textStatus + "data: " + data);
        },
        dataType: "json"
    });
}

function searchProducts(url, locale, productImagePath, thisUri, noProductsFound, pages, sorting, category, price, color) {
	var inpPage = document.getElementById("inpPage").value;
	var inpSearch = document.getElementById("inpSearch").value;

    $.ajax({
        type: 'GET',
        url: url,
        data: {'cmd': 'search_products', 'locale': locale, 'inpPage': inpPage, 'inpSearch': inpSearch },
        success: function(data) {
            if (data.status == 'success') {
                document.getElementById("productPart").innerHTML = renderProducts(data.count, data.currentPage, data.currentSort, data.products, productImagePath, thisUri, noProductsFound, pages, sorting, category, price, color);
                document.getElementById("sort_block").style.display = "none";
            } else if (data.status == 'error') {
                for (var l = 0; l < data.errors.length; l++) {
                    var e = data.errors[l];
                    alert('ERROR: ' + e.name + '\n\n' + e.stacktrace);
                }
            } else {
                alert('Undefined status: ' + data.status);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("error. textStatus" + textStatus + "data: " + data);
        },
        dataType: "json"
    });
}

function OpenWindowProductImage(){
	var win = window.open('', 'popup_image' + Math.round(Math.random() * 1000), 'width=500px,height=500px,menubar=0,location=0,resizable=0,scrollbars=1,directories=0,scroll=1,status=0,menubar=0,locationbar=0,statusbar=0,titlebar=0,toolbar=0');
	win.document.open();
	win.document.write("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.0 Transitional//EN'><html><head><title>Image</title><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'></head><body><img src='" + document.getElementById("product_pic").src.replace("&width=240&height=240","") + "' alt=''></body></html>");
	win.document.close();
}

function ChangeColor(color){
	document.getElementById("inpPage").value = 0;
	document.getElementById("inpColor").value = color;
}

function ResetColor() {
	document.getElementById("inpPage").value = 0;
	document.getElementById("inpColor").value = "";
}

var activeColor = null;

function setImages (requestColor) {
	var images = document.getElementById("activeColors").getElementsByTagName("IMG");
	for(var i = 0; i < images.length; i++) {
		var img = images[i];
		if(requestColor != '' && new RegExp(requestColor, "i").test(img.src)) {
			img.style.display = 'block';
			img.className = "active";
			activeColor = requestColor;
		}
	}
}

function hideImages() {
	var images = document.getElementById("activeColors").getElementsByTagName("IMG");
	for(var i = 0; i < images.length; i++) {
		images[i].style.display='none';
	}
}

function toggleColor(color) {
	var img = document.getElementById(color);
	if (img.className == "active") {
		ResetColor();
		img.className = "";
		hideImage(color);
	} else {
		if (activeColor != null) {
			document.getElementById(activeColor).className = "";
			hideImage(activeColor);
		}
		img.className = "active";
		activeColor = color;
		ChangeColor(img.id);
	}
}

function displayImage(imgId) {
	document.getElementById(imgId).style.display = 'block';
}

function hideImage(imgId) {
	var img = document.getElementById(imgId);
	if (img.className != 'active') {
		img.style.display='none';
	}
}

function ZoomImage(obj){
	obj.width = 62;
	obj.height = 62;
	obj.style.top = "-5px";
	obj.style.left = "-5px";
	obj.style.cursor = "pointer";
}

function UnzoomImage(obj){
	obj.width = 52;
	obj.height = 52;
	obj.style.top = "0";
	obj.style.left = "0";
	obj.style.cursor = "default";
}

function getEventTarget (e) {
	e = e || event;
	return e.srcElement || e.target;
}

function changeMetaInfo(newTitle, newDescription, newImage){
	document.title = newTitle;
	var metas = document.getElementsByTagName("meta");
	for (i=0; i<metas.length; i++){
		if (metas[i].name == "description") {
			metas[i].content = newDescription;	
		}
	}
	var links = document.getElementsByTagName("link");
	for (k=0; k<links.length; k++){
		if (links[k].rel == "image_src") {
			links[k].href = newImage; 
		}
	}
	
}	