function window_open(a, b, c, d, e, f) {
    _top = Math.ceil((screen.height - c) / 2);
    _left = Math.ceil((screen.width - b) / 2);
    if (e != true) {
        var g = "no"
    } else {
        var g = "yes"
    }
    if (typeof f != "undefined" && f == true) {
        var f = "yes"
    } else {
        var f = "no"
    }
    if (d == undefined) {
        d = Math.round(999999 * Math.random())
    }
    new_win = window.open(a, d, "width=" + b + ",height=" + c + ",location=" + f + ",status=no,toolbar=no,menubar=no,resizable=yes,scrollbars=" + g + ",top=" + _top + ",left=" + _left);
    new_win.focus();
    return new_win
}
function addslashes(str) {
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\0/g,'\\0');
	return str;
}
function changeStock(a) {
    $.cookie("stock", a, {
        path: "/",
        expires: 1
    })
}

function changeView(a, b) {
    $cookie = $.cookie("view");
    if ($cookie == a) return;
    $(b).parent().find("a").removeAttr("id");
    $(b).attr("id", "selected");
    $view = a;
    $.cookie("view", $view, {
        path: "/",
        expires: 1
    });
    update_items();
}
function checkFilterCookie(a, b) {
    $cookie = $.cookie("filters_" + b + "_" + a);
    if ($cookie) {
        $.cookie("filters_" + b + "_" + a, false, {
            path: "/",
            expires: -1
        })
    } else {
        $.cookie("filters_" + b + "_" + a, true, {
            path: "/"
        })
    }
}
function changePageCookie(a){
	$.cookie("page", a, {
        path: "/",
		domain: ".dataleks.lv",
        expires: 1
   });
   $('input[name=page]').val(a);
}

function pages(a) {
    $page = $("input[name=page]").val();
	
    $num_pages = Math.ceil(a / $per_page);
    $pages = "";
    $step = 4;
    $start = 1;
    $end = $step;
    $steps = Math.ceil($page / $step);
    if ($steps > 1) {
        $start = $step * ($steps - 1);
        $end = $step * $steps
    }
    $end = $end > $num_pages ? $num_pages : $end;
    for ($x = $start; $x <= $end; $x++) {
        if ($x > $num_pages) break;
        $pages += "<a onclick=\"changePageCookie(" + $x + '); update_items()" href="javascript:void(0)" ' + ($page == $x ? 'class="selected"' : "") + ">" + $x + "</a>";
        if ($x == $end && $num_pages > $step && $end < $num_pages) {
            $pages += "<a onclick=\"changePageCookie(" + ($x + 1) + '); update_items()" href="javascript:void(0)">></a>'
        }
    }
    return $pages
}

function update_items() {
	$("span#items").fadeOut();
    $serialize = $("form#filters").serialize();
    $.ajax({
        url: "/js/ajax.php",
        type: "GET",
        dataType: "json",
        data: {
            "do": "update-items",
            data: $serialize
        },
        success: function (a) {
            $("span#items").html(null);
            if (a[1] < $per_page) {
                $(".sort-block-pages").html('<a class="selected">1</a>')
            } else {
                $(".sort-block-pages").html(pages(a[1]))
            }
            for (var b in a[0]) {
                root = a[0][b];
                $html = '<div id="' + (root["item_special"] > 0 ? "special" : "") + '" class="sub-item' + ($view == "list" ? "-list" : "") + ((root["item_stock"] == 0 && root["item_stock_shop"] == 0) ? " empty" : "") + ' item-' + root["item_id"] + '">';
                $html += '<a href="' + root["item_href"] + '" class="' + ($view == "list" ? "list-img" : "") + '"><img id="image" border="0" width="' + ($view == "list" ? "94" : "198") + '" alt="" src="/uploads/items/small/' + (root["image_id"] ? root["image_id"] : "no-avatar.png") + '"></a>';
                $html += '<a class="item-desc-container' + ($view == "list" ? "-list" : "") + '" href="' + root["item_href"] + '">';
                $html += '<div id="title" class="sub-item-name' + ($view == "list" ? "-list" : "") + '">' + root["item_title"] + "</div>";
                if ($view == "list") $html += '<div class="sub-item-desc-list">' + root["item_desc"] + "</div>";
                $html += "</a>";
                $html += '<div id="price" class="sub-item-price' + ($view == "list" ? "-list" : "") + '">' + (root["item_special"] > 0 ? "<del>" + root["item_price"] + " Ls</del> <b>" + root["item_special"] + " Ls</b>" : root["item_price"] + " Ls") + "</div>";
                $html += '<a class="sub-item-buy' + ($view == "list" ? "-list" : "") + '"  href="javascript:;" onclick="addItemToCart(' + root["item_id"] + ');">' + $locale["buy"] + '</a>';
                $html += "</div>";
                $("span#items").append($html)
            }
            if ($view == "list") $("span#items").append('<div class="list-flat"></div>');
			if(a[1] == 0)
				$("span#items").html($locale['no-items']);
            $("span#items").fadeIn('slow');
        }
    })
}
function update_filters(){
	$serialize = $("form#filters").serialize();
	$.ajax({
		url: "/js/ajax.php",
		type: "GET",
		dataType: "json",
		data: {
			"do": "update-filters",
			data: $serialize
		},
		success: function (a) {
			for (var b in a) {
				$filter_id = a[b]["filter_id"];
				$("span#filter_" + $filter_id).find("div.points input").attr("disabled", true);
				for (var c in a[b]["options"]) {
					$("span#filter_" + $filter_id + " input#filter_" + $filter_id + "_" + a[b]["options"][c]["value_id"]).attr("disabled", false)
				}
			}
		}
	})
}
function update_search(){
	//$('input[name=search]').val(value);
	update_items();
	update_filters();
	
}
$(function () {
    $left_menu = $("div.left-menu");
    if ($left_menu.length > 0) {
        $left_menu.find("span a div.link-arrow div").click(function () {
            $parent = $(this).parents("span");
            console.log($parent);
            $this = $(this);
            $points = $parent.find("div.points");
            if ($points.length) {
                if ($points.is(":hidden")) {
                    $points.show();
                    $parent.find(".link-arrow div").removeClass("arrow-down").addClass("arrow-up")
                } else {
                    $points.hide();
                    $parent.find(".link-arrow div").removeClass("arrow-up").addClass("arrow-down")
                }
            }
            return false
        });
        $("div.left-menu a div.link-title").click(function () {
            return true
        })
    }
    $cart = $(".cart-container-centered");
    if ($cart.length > 0) {
        $("select#item_count").change(function () {
            $parent = $(this).parents("div.cart-container-item");
            $id = $parent.attr("id");
            $price = $parent.find("div.cart-container-item-price b").html();
            $price = parseFloat($price);
            $value = this.value;
            $tmp = Math.round($price * $value * 100) / 100;
            $tmp = parseFloat($tmp);
            if (strpos($tmp, ".") !== false) $tmp = correctNumberEnding($tmp, ".");
            $parent.find("div.cart-container-item-price span").html($tmp);
            $.ajax({
                url: "/js/ajax.php",
                type: "GET",
                dataType: "text",
                data: {
                    "do": "change-item-count",
                    value: $value,
                    id: $id
                },
                success: function (a) {
                    if (a.indexOf('success') != -1)
                    	countTotalPrice();
                    else
                    	console.log(a)
                }
            })
        })
    }
    $filter_box = $(".filter-box");
    if ($filter_box.length > 0) {
        $filter_box.find("a.title").click(function () {
            $parent = $(this).parents("span");
            $this = $(this);
            $points = $parent.find("div.points");
            if ($points.length) {
                if ($points.is(":hidden")) {
                    $points.show();
                    $parent.find(".link-arrow div").removeClass("arrow-down").addClass("arrow-up")
                } else {
                    $points.hide();
                    $parent.find(".link-arrow div").removeClass("arrow-up").addClass("arrow-down")
                }
            }
            return false
        });
        $filter_box.change(function () {
            $serialize = $("form#filters").serialize();
            update_items();
            update_filters();
        })
    }
});
check = function (a, b) {
    $event = $(a);
    $value = $event.val();
    var c;
    if (b == "email") {
        c = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
    } else if (b == "phone") {
        c = /^[+\d]{8,12}$/
    } else if (b == "pk") {
        c = /^([\d]{6})-([\d]{5})$/
    } else if (b == "name") {
        c = /^[a-zA-Z0-9\"\-\.\,\u0100\u0101\u0112\u0113\u016a\u016b\u012a\u012b\u0160\u0161\u0122\u0123\u0136\u0137\u013b\u013c\u017d\u017e\u010c\u010d\u0145\u0146\s]{1,50}$/
    } else if (b == "address") {
        c = /^[.,\w\s\/\d-\u0100\u0101\u0112\u0113\u016a\u016b\u012a\u012b\u0160\u0161\u0122\u0123\u0136\u0137\u013b\u013c\u017d\u017e\u010c\u010d\u0145\u0146]{1,250}$/
    } else if (b == "reg_nr") {
        c = /^[\d]{11}$/
    } else if (b == "date") {
        c = /^([\d]{2}).([\d]{2}).([\d]{4})$/
    } else if (b == "pvn") {
        c = /^[0-9A-Z]{13}$/;
        if (strpos($value, "LV") === false) {
            $event.css("border", "1px solid red");
            return false
        }
    }
    if (!c.test($value)) {
        $event.css("border", "1px solid red");
        return false
    }
    $event.css("border", "1px solid green");
    return true
};
var ordersubmit=false;
orderFinish = function () {
	var c = $("input[name=delivery_type]:checked").val();
	if(ordersubmit){
		if(c == 1){
			if(check($("input[name=delivery_address]"), "address")){
				$('form#cart').submit()
			}
		} else {
			$('form#cart').submit()
		}
	}
};
nextStep = function (a) {
    var b, c, d;
    b = $("input[name=details_type]:checked").val();
    if (a == 0) {
		if (b == 0) {
            if (check($("input[name=user_name]"), "name") & check($("input[name=user_phone]"), "phone") & check($("input[name=user_email]"), "email")) {
                openNextStep(a);
            }
        } else if (b == 1) {
			if (check($("input[name=company_name]"), "name") & check($("input[name=company_reg_nr]"), "reg_nr") & check($("input[name=company_phone]"), "phone") & check($("input[name=company_jur]"), "address") & check($("input[name=company_fiz]"), "address") & check($("input[name=company_banka]"), "address") & check($("input[name=company_bankas_konts]"), "address") & check($("input[name=company_email]"), "email")) {
                openNextStep(a);
            }
        }
    } else if (a == 1) {
        c = $("input[name=payment_type]:checked").val();
        if (c == 1) {
		if (b == 0 && check($("input#personal_number0"), "pk") || b == 1 && check($("input[name=company_reg_nr]"), "reg_nr")){
			openNextStep(a);
			ordersubmit=true;
		}
        } else if (c == 2) {
		openNextStep(a);
		ordersubmit=true;
        } else if (c == 0) {
		openNextStep(a);
		ordersubmit=true;
        }
    }
};
openNextStep = function (a) {
    $("div#step_" + (a + 1)).css("opacity", "1").find("input").attr("disabled", false)
};
strpos = function (a, b, c) {
    a = "" + a + "";
    var d = a.indexOf(b, c);
    return d >= 0 ? d : false
};
explode = function (a, b, c) {
    b = "" + b + "";
    return b.split(a, c)
};
correctNumberEnding = function (a, b) {
    $explode = explode(b, a);
    if ($explode[1].length < 2) a += "0";
    return a
};
lizingFunc = function () {
	//$price = $price.replace(',','');
    $down_payment = Math.round($price * ($("select#down-payment").val() / 100) * 100) / 100;
    if (strpos($down_payment, ".") !== false) $down_payment = correctNumberEnding($down_payment, ".");
    $("span#span-down-payment").text($down_payment);
    $down_payment = parseFloat($down_payment);
    $tmp_price = $price - $down_payment;
    $each_month = Math.round($tmp_price / $("select#lease-period").val() * 100) / 100;
    if (strpos($each_month, ".") !== false) $each_month = correctNumberEnding($each_month, ".");
    $("span#span-each-month").text($each_month);
    $("select#down-payment").change(function () {
        $down_payment = Math.round($price * (this.value / 100) * 100) / 100;
        if (strpos($down_payment, ".") !== false) $down_payment = correctNumberEnding($down_payment, ".");
        $("span#span-down-payment").text($down_payment);
        $down_payment = parseFloat($down_payment);
        $tmp_price = $price - $down_payment;
        $("select#lease-period").change()
    });
    $("select#lease-period").change(function () {
        $each_month = Math.round($tmp_price / this.value * 100) / 100;
        if (strpos($each_month, ".") !== false) $each_month = correctNumberEnding($each_month, ".");
        $("span#span-each-month").text($each_month)
    })
};
overlay = function () {
    $div = $("<div>").attr("id", "overlay");
    $("body").append($div)
};
itemAddedToCart = function (a, b, c) {
    $makeup = '<div id="alert"><div id="alert-header"><div id="alert-close"></div><div id="alert-header-text">'+$locale['alert'][0]+' "<b>' + a + '</b>" '+$locale['alert'][1]+' <a href="/' + $lang + '/cart/">'+$locale['alert'][2]+'</a></div></div><div id="alert-body"><div class="item-img"><img src="' + c + '" height="110"/></div><div class="arrow"></div><div class="cart-img"></div></div><div id="alert-footer"><div><a href="/' + $lang + '/cart/" class="buy-item-button">'+$locale['send-order']+'</a></div><div>'+$locale['alert'][3]+'</div><div><a href="javascript:;" class="return">'+$locale['return']+'</a></div></div></div>';
    $("body").append($makeup);
    $("#alert").fadeIn();
    $count = $(".cart-zone .cart-details a").eq(0).find("b").html();
    $count = parseInt($count);
    $(".cart-zone .cart-details a").eq(0).find("b").html($count + 1);
    $count = $(".cart-zone .cart-details a").eq(1).find("b").html();
    $count = parseFloat($count);
	//b = b.replace(',','');
	b = parseFloat(b);
    $count = Math.round(($count + b) * 100) / 100;
    $(".cart-zone .cart-details a").eq(1).find("b").html($count + " Ls");
    $(".cart-zone a[class=cart-img-empty]").removeClass("cart-img-empty").addClass("cart-img-full");
    $(document).keyup(function (a) {
        if (a.keyCode == 27) {
            $("#alert").fadeOut(function () {
                $(this).remove();
                $("#overlay").remove()
            })
        }
    });
    $("#alert-close, a.return").click(function () {
        $("#alert").fadeOut(function () {
            $(this).remove();
            $("#overlay").remove()
        })
    })
};

addItemToCart = function (a) {
    overlay();
	$title = $('div.item-' + a).find('#title').html();
	$price = $('div.item-' + a).find('#price').html();
	$price = $price.replace(/[^0-9.,]/ig,'');
	$image = $('div.item-' + a).find('#image').attr('src');
    $.ajax({
        url: "/js/ajax.php",
        type: "GET",
        dataType: "text",
        data: {
            "do": "add-item",
            id: parseInt(a)
        },
        success: function (rs) {
            if (rs.indexOf('success') != -1) 
            	itemAddedToCart($title, $price, $image);
            else 
            	console.log(rs)
        }
    })
};

countTotalPrice = function () {
    $total = 0;
    $items = 0;
    $("div.cart-container-item").each(function () {
        $items++;
        $price = $(this).find(".cart-container-item-price span").html();
        $price = parseFloat($price);
        $total += $price
    });
    if ($total > 0) {
        $total = Math.round($total * 100) / 100;
        if (strpos($total, "."))
        	$total = correctNumberEnding($total, ".");
        else
        	$total += '.00';
    }
    $("div.cart-summ b").html($total + " Ls");
    $("div.cart-zone div.cart-details a").eq(0).find("b").html($items);
    $("div.cart-zone div.cart-details a").eq(1).find("b").html($total + " Ls");
    if ($items == 0) $(".cart-zone a[class=cart-img-full]").removeClass("cart-img-full").addClass("cart-img-empty")
};

itemRemovedFromCart = function (a) {
    $("div.cart-container-item#" + a).fadeOut(function () {
        $(this).remove();
        countTotalPrice()
    })
};

removeItemFromCart = function (a) {
	$.ajax({
        url: "/js/ajax.php",
        type: "GET",
        dataType: "text",
        data: {
            "do": "remove-item",
            id: parseInt(a)
        },
        success: function (rs) {
            if (rs.indexOf('success') != -1){
            	itemRemovedFromCart(a);
				showOrderForm();
			}
            else 
            	console.log(rs)
        }
    })
}

var showOrderForm = function(){
	$items = $('div.cart-container-item').length;
	if($items.length < 1){
		$('div.cart-buy-container').fadeOut();
		return false;
	}else{
		$('div.cart-buy-container').fadeIn();
	}
}
