$(document).ready(function() {
	$("a.dashed").live("mousedown", function(){
  $("a.dashed").overlay({
			// some expose tweaks suitable for modal dialogs
			expose: {
				color: '#000',
				loadSpeed: 200,
				opacity: 0.8
			},
			onLoad:  function() {
  			this.getOverlay().insertAfter('#exposeMask');
			},
			closeOnClick: true
	    });

	});
	
	w_width = $("#header").width() - 480;
	$(".adv-goods").css("width", w_width);
	$(window).resize(function() {
    	w_width = $("#header").width() - 480;
	    $(".adv-goods").css("width", w_width);
	});


	anchor.init()

	$.fn.addCart = function(url, id) {
	    var data = '&id=' + parseInt(id);
	    var rbuttons = getElementsByClassName("r" + id, 'input');
	    if (rbuttons.length > 1) { //then it's a radio-buttons collection
		    var price_is_ok = true;
	        data += "&price=" + rbuttons[0].value.toString();
	    } else { //then there's only one price and the element is an <input type="hidden" />
	        var price_is_ok = true;
	        data += "&price=" + rbuttons[0].value.toString();
	    }
	    
	    if (price_is_ok) { //price is selected
			$.ajax({
				type: "GET",
				url: url,
				data: data,
				beforeSend: function () {
					$("#lo").html("<span class='lo-txt'>Обновление корзины...</span>");
				},
				complete: function () {
					$("#lo").html("");
					var api = $("a.dashed").overlay({
						// some expose tweaks suitable for modal dialogs
						expose: {
							color: '#000',
							loadSpeed: 200,
							opacity: 0.8
						},
						closeOnClick: true,
						onLoad:  function() {
  						this.getOverlay().insertAfter('#exposeMask');
						},
						api: true
					});
                  api.load();
				},
				success: function (data) {
                    $("#cart-goods").html(data);
				}
			});
	    } else
	        alert('Скажи "НЕТ!" халяве - не забудь выбрать цену! (-:');
	}

	$(".inp, .inp-name, .short-inp, .short-inp2, .customer-table textarea").focus(function(){
		$(this).css("border", "1px solid #df5006").css("color", "#df5006");
	});
	$(".inp, .inp-name, .short-inp, .short-inp2, .customer-table textarea").blur(function(){
	    $(this).css("border", "1px solid #B5B5B5").css("color", "#B5B5B5");
	});
});

anchor = {
	init : function()  {
		$("a.sub-links").click(function () {
			elementClick = $(this).attr("href")
			destination = $(elementClick).offset().top - 50;
			$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 1100 );
		  	return false;
		})
	}
}

function gotopage (id, catId) {
    if (id == 'all')
        document.location = '/catalog/' + catId;
    else
        document.location = '/catalog/' + id;
}

function getBrands(url, id) {
    var req = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    req.onreadystatechange = function() {
        switch (req.readyState) {
            case 1: case 2: case 3:
                document.getElementById('lo').innerHTML = '<span class="lo-txt">Получение категорий...</span>';
            break;
            case 4:
                document.getElementById('brands').innerHTML = req.responseText;
                document.getElementById('lo').innerHTML = '';
            break;
        }
    }
        url += '?id=' + id;
        req.open("GET", url, true);
        req.setRequestHeader("Content-type", "application/x-www-form-urlencoded, charset=utf-8");
        req.setRequestHeader("Connection", "close");
        req.send(null);
}

function getElementsByClassName(strClass, strTag, objContElm) {
  strTag = strTag || "*";
  objContElm = objContElm || document;
  var objColl = objContElm.getElementsByTagName(strTag);
  if (!objColl.length &&  strTag == "*" &&  objContElm.all) objColl = objContElm.all;
  var arr = new Array();
  var delim = strClass.indexOf('|') != -1  ? '|' : ' ';
  var arrClass = strClass.split(delim);
  for (var i = 0, j = objColl.length; i < j; i++) {
    var arrObjClass = objColl[i].className.split(' ');
    if (delim == ' ' && arrClass.length > arrObjClass.length) continue;
    var c = 0;
    comparisonLoop:
    for (var k = 0, l = arrObjClass.length; k < l; k++) {
      for (var m = 0, n = arrClass.length; m < n; m++) {
        if (arrClass[m] == arrObjClass[k]) c++;
        if (( delim == '|' && c == 1) || (delim == ' ' && c == arrClass.length)) {
          arr.push(objColl[i]);
          break comparisonLoop;
        }
      }
    }
  }
  return arr;
}

function mark(id, className) {
    $('.' + className).css('background', '#fff');
	$('#' + id).css('background', '#F7F7F7');
}


function cartAction(url, act, id, el, price) {
    var req = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    req.onreadystatechange = function() {
        switch (req.readyState) {
            case 1: case 2: case 3:
                document.getElementById('lo').innerHTML = '<span class="lo-txt">Обновление корзины...</span>';
            break;
            case 4:
                if (act == 'plus') {
                    document.getElementById('number-' + id + '-' + price).innerHTML = parseInt(document.getElementById('number-' + id + '-' + price).innerHTML) + 1;
                    document.getElementById('info').innerHTML = req.responseText;
                } else {
                    if (act == 'minus') {
                        if (parseInt(document.getElementById('number-' + id + '-' + price).innerHTML) - 1 > 0) {
                            document.getElementById('number-' + id + '-' + price).innerHTML = parseInt(document.getElementById('number-' + id + '-' + price).innerHTML) - 1;
                            document.getElementById('info').innerHTML = req.responseText;
                        } else {
                            document.getElementById('tr-' + id + '-' + price).parentNode.removeChild(document.getElementById('tr-' + id + '-' + price));
                            document.getElementById('info').innerHTML = req.responseText;
                        }
                    } else if (act == 'delete') {
                        document.getElementById('tr-' + id + '-' + price).parentNode.removeChild(document.getElementById('tr-' + id + '-' + price));
                        document.getElementById('info').innerHTML = req.responseText;
                    }
                    if ($('.trr').html() == null) $(".close").click();
                }
                document.getElementById('lo').innerHTML = '';
            break;
        }
    }
        url += '&type=' + act;
        req.open("GET", url, true);
        req.setRequestHeader("Content-type", "application/x-www-form-urlencoded, charset=utf-8");
        req.setRequestHeader("Connection", "close");
        req.send(null);
}

function emptyCart(url) {
    var req = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    req.onreadystatechange = function() {
        switch (req.readyState) {
            case 1: case 2: case 3:
                document.getElementById('lo').innerHTML = '<span class="lo-txt">Очистка корзины...</span>';
            break;
            case 4:
                document.getElementById('cart-goods').innerHTML = req.responseText;
                document.getElementById('product').innerHTML = '';
                document.getElementById('lo').innerHTML = '';
            break;
        }
    }
        req.open("GET", url, true);
        req.setRequestHeader("Content-type", "application/x-www-form-urlencoded, charset=utf-8");
        req.setRequestHeader("Connection", "close");
        req.send(null);
}

function showHide(id) {
    if (document.getElementById(id).style.display == 'block') {
        document.getElementById(id).style.display = 'none';
    } else {
        document.getElementById(id).style.display = 'block';
    }
}

function showSection(id) {
	for (i = 1; i <= 4; i ++) {
		var section = String('section' + i);
		if (section == id) {
		    document.getElementById(section).style.display = 'block';
		} else
		    document.getElementById(section).style.display = 'none';
	}
}


showImg = function (el, id) {
     for (i = 0; i <= 2; i ++) {
         div = 'photo' + i;
         div_small = 'photo-small-' + i;
         if (document.getElementById(div) && i != id) {
             document.getElementById(div).style.display = 'none';
             document.getElementById(div_small).style.borderBottom = '3px solid #fff';
         }
     }
     div_id = 'photo' + id;
     document.getElementById(div_id).style.display = 'block';
     el.style.borderBottom = '3px solid #DC0793';
}

showInfo = function (id) {
    var blocks = new Array('description', 'characteristics', 'reviews');
    for (j = 0; j < blocks.length; j ++) {
	    if (id != blocks[j]) {
		    document.getElementById(blocks[j]).style.display = 'none';
            document.getElementById(blocks[j] + '-txt').className = 'passive';
        }
    }
    document.getElementById(id).style.display = 'block';
    document.getElementById(id + '-txt').className = 'active';
}

function number_format (number, decimals, dec_point, thousands_sep) {
    // Formats a number with grouped thousands
    //
    // version: 906.1806
    // discuss at: http://phpjs.org/functions/number_format    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival    // +     input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +     improved by: davook
    // +     improved by: Brett Zamir (http://brett-zamir.me)
    // +     input by: Jay Klehr
    // +     improved by: Brett Zamir (http://brett-zamir.me)    // +     input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'    // *     example 10: number_format('1.20', 2);
    // *     returns 10: '1.20'
    // *     example 11: number_format('1.20', 4);
    // *     returns 11: '1.2000'
    // *     example 12: number_format('1.2000', 3);    // *     returns 12: '1.200'
    var n = number, prec = decimals;

    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);        return (Math.round(n*k)/k).toString();
    };

    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
     var abs = toFixedFix(Math.abs(n), prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);    } else {
        s = s.replace('.', dec);
    }

    var decPos = s.indexOf(dec);    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';    }
    return s;
}

function calculateDelivery(val) {
   if (parseInt(val)) {
	   document.getElementById('delivery').innerHTML = ' + ' + number_format(val, 0, '', ' ') + ' р.';
	   document.getElementById('whole_amount_block').innerHTML = '<span class="price">' + number_format((parseInt(document.getElementById('whole_amount').value) + parseInt(val)), 0, '', ' ') + ' р.</span>';

   }
}
