function JSend()
{
    var _this = this;
    this.uid = 'jSend';
    this.options = {};
    this.bSend = false;
    this.url = null;
    this.data = null;
    this.callback = null;
    this.method = null;
    this.idTimeout = 0;
    this.timeout = 2000

    this.shiftObj = function(obj)
    {
        var arr=[];
        if(_this.sizeObj(obj)){
            var i = null;
            for(i in obj){break}
            arr = obj[i]
            delete obj[i]
        }
        return arr;
    }

    this.sizeObj = function(obj)
    {
        var n=0;
        for(var i in obj){n++;}
        return n;
    }

    this.count = function()
    {
        return _this.sizeObj(_this.options)
    }

    this.send = function()
    {
        if(!_this.bSend && _this.sizeObj(_this.options) ){
            _this.bSend = true
            showImgLoader();
            var arrJ = _this.shiftObj(_this.options)
            _this.url      = arrJ[0];
            _this.data     = arrJ[1];
            _this.callback = arrJ[2];
            _this.method   = arrJ[3];
            $.ajax({
                type: _this.method,
                url:  _this.url,
                data: _this.data,
                cache: false,
                success:_this.callback
            });
        }

        if(_this.sizeObj(_this.options)){
            clearTimeout(_this.idTimeout)
            _this.idTimeout = setTimeout(_this.send, 150)
        }
    }

    this.setOptions = function(url, data, callback, method)
    {
        _this.options[_this.uid] = [url,data,callback,method]
        //_this.options.push([url,data,callback,method])
    }

    this.setUID = function(uid)
    {
        _this.uid = (uid?uid:'jSend');
    }

    this.sendData = function(url, params, callback, method, uid)
    {
        _this.setUID(uid)
        _this.setOptions(url, params, callback, method)
        _this.sendTimeout()
    }

    this.sendTimeout = function(time)
    {
        clearTimeout(_this.idTimeout)
        var timeout = _this.timeout
        if(time){
            timeout = time;
        }
        _this.idTimeout = setTimeout(_this.send, timeout)
    }
}

jcart = new JSend()

var count = 1;

function converting(id, params)
{
	$('#purchase').show();
    $('#oblast').html('');
    $('#region').html('');
    $('#delivery').html('');
    $('#dservice').html('');
    $('#payment').html('');
    $('#user').html('');
    $('#purchase').fadeOut();

    count = parseInt(number($('#count'+id).val()));

    if (isNaN(count) || count<1) {
        jcart.timeout = 5000
        count = 1;
    } else {
        jcart.timeout = 2000
    }
    var pack = parseInt(number($('#pack'+id).val()));
    if (isNaN(pack) || pack<0) {
        jcart.timeout = 5000
        pack = 0;
    } else {
        jcart.timeout = 2000
    }


    var uid ='';
    var urlParams = '';
    var i = null;
    for(i in params){
        urlParams += i + '/' + params[i] + '/'
        uid += '_' + params[i]
    }

    httpURL = '/ajorder/operation/change/id/'+ id + '/count/' + count + '/pack/' + pack + '/' + urlParams;
    jcart.sendData(httpURL,null,reConverting,'GET','converting'+id+uid)
}

function reConverting(html)
{
    removeImgLoader()
    jcart.bSend = false
    var myObject = Json.evaluate(html);
    var id        = myObject['id'];
    var accessory = myObject['accessory'];
    var sufix = (accessory?'_'+accessory:'');
    $('#count').text(myObject['count']);
    $('#count'+id+sufix).val(myObject['countItem']);
    $('#pack'+id+sufix).val(myObject['packItem']);
    $('#price').text(myObject['money']);
    $('#ajax_total').text(myObject['money']);
    $('#ajax_coast'+id+sufix).text(myObject['price']);

    if (count > myObject['countItem']) {
    	var pos = $('#count'+id+sufix).offset();
    	var left = pos.left + 60;
    	var top = pos.top;

    	$('#msgcount').text(myObject['countItem']);
    	$('#msgCount').css('left',left);
    	$('#msgCount').css('top', top);
    	$('#msgCount').css('z-index',1003);
    	$('#msgCount').show();
    }
    $('#purchase').fadeIn();
}

function isNumeric(my)
{
    if(isNaN(parseInt(my.value)) || parseInt(my.value)==0) {
        my.value = 1;
    }
}

function isNumeric2(my)
{
    if(isNaN(parseInt(my.value)) || parseInt(my.value)==0) {
        my.value = 0;
    }
}

function loadDelivery(my)
{
	//alert(my);
    $('#delivery').html('');
    $('#dservice').html('');
    $('#payment').html('');
    $('#user').html('');

    if(my > 0 ) {
        var str = 'id=' + my;
        createCookie('city_id', my, false);
        //createCookie('city_id', 10, false);

        var httpURL = '/ajorder/operation/xdelivery/';
        showImgLoader();
        $.post(httpURL, {id: my}, reDelivery, "json");
    }
}

//уРПУПВ ДПУФБЧЛЙ:
function reDelivery(data)
{
	//console.dir(data);
    removeImgLoader();
    if (!(data=checkStatus(data))) {
        return;
    }

    if (data['count']==0) {
        var httpURL = '/ajorder/operation/user/';
        $.post(httpURL, {payment: '0'}, reUser);
    } else {
        $('#delivery').attr('innerHTML', data['delivery']);
        if(data['count']==1){
            //loadDeliveryService(2,/*data['id'],*/ data['delivery']);
            loadDeliveryService(data['id'], data['delivery']);
        }
    }
    lastAnchor();
}

function loadDeliveryService(id, deliverry)
{
    $('#dservice').html('');
    $('#payment').html('');
    $('#user').html('');

    var reg = $('#region_id').attr('value');
    if (id > 0 && reg > 0)	{
        var str = 'delivery=' + id + '&region=' +reg
        var httpURL = '/ajorder/operation/service/';
        showImgLoader();
        $.post(httpURL, {delivery:id, region:reg}, reService,'json');
    }
}

//уМХЦВБ ДПУФБЧЛЙ:
function reService(data)
{
    removeImgLoader();
    if (!(data=checkStatus(data))) {
        return;
    }
    $('#dservice').attr('innerHTML',data.html);
    if(data['count']==1) {
        loadPayment(data['id'], data['sid']);
    }
    lastAnchor();
}

function loadPayment(id, sid)
{
    $('#user').html('');
    createCookie('servise_id',id);

    var payment = document.getElementById('payment');
    if (payment) {
        //var str = 'service=' + id + '&dservice=' + sid;
        var httpURL = '/ajorder/operation/payment/';
        showImgLoader();
        $.post(httpURL, {service:id, dservice:sid}, rePayment, "json");
    }
}

function rePayment(data)
{
    removeImgLoader();
    if (!(data=checkStatus(data))) {
        return;
    }
    $('#payment').attr('innerHTML',data.html).blur();
    if(data['count']==1) {
        loadUser(data['id']);
    }
    else
    {
    	loadUser(data['id']);
    }
    pppay();
    lastAnchor();
}

function loadUser(id, s)
{
	//alert(id);
    $('#user').html('');

    showPresentForm('present_id');
    if (id) {
        var httpURL = '/ajorder/operation/user/';
        showImgLoader();
        $.post(httpURL, {payment:id}, reUser, "json");
    }
}


function reUser(data)
{
	//console.dir(data);
    removeImgLoader();
    if (!(data=checkStatus(data))) {
        return;
    }
    //$('#user').slideUp('slow', function(){
    	//$('#user').attr('innerHTML', data).slideDown('slow');
    //});

    $('#user').attr('innerHTML', data);
    //if(s!=1)
    $('#adres').html($('#aadres').html());
    $('#aadres').html('');
    $('#names').html($('#nnames').html());
    $('#nnames').html('');
	//$('.check_red_error').blur();
    $('#summ').html($('#ssum').html());
    $('#buy_but').html($('#buy_butt').html());
    lastAnchor();
}

function pppay()
{
	//alert('ppay');
   	$('#pppay').html($('#ppay').html());
    $('#ppay').remove();
}



function code(code)
{
	$('#error_message').hide();
	$("#sertificat_success").hide();
	$("#sertificat_price").html(0);
	if (code) {
		var httpURL = '/ajorder/operation/code/';
        showImgLoader();
        $.post(httpURL, {code:code}, reCode, "json");
	}
}

function reCode(data)
{
	removeImgLoader();
	if (data['status'] == 1) {
		$("#sertificat_success").show();
		$("#sertificat_price").html(data['price']);
		if ($("#oblast").html()) {
			loadOblast('first');
		}
	} else {
		$('#error_message').show();
	}

}


function lastAnchor()
{
    //    window.location.href="#lastAnchor";
    //	var ajax = null;
    //	if(ajax = document.getElementById("TB_ajaxContent")) {
    //	    //ajax.focus();
    //		ajax.scrollTo();
    //	}
    //target=$('#TB_ajaxContent');
    //var targetOffset = target.offset().top;
    //document.getElementById("cart-content").scrollTop = 1000;
    //$('html,body').animate({scrollTop: targetOffset}, 1000);
}
function checkStatus(data) {
    if (data['status']!=0) {
        showAmountMessage(data['data']);
        return 0;
    } else {
        return data['data'];
    }
}

function loadAuth(name, login)
{
    showImgLoader();
    var httpURL = '/ajorder/operation/auth/';
    $.post(httpURL, {user_email:name, user_password:login}, reAjaxAuth, "json");
}

function reAjaxAuth(data)
{
    removeImgLoader();
    if (!(data=checkStatus(data))) {
        return;
    }
    if (data['auth']) {
        loadOblast('first');
        $('#login_btn').hide();
        $('#login_form').hide();
        $('#myfarboozon').show();
//        loadRegion('first');
    } else {
        $('#login_order_message').css('display','none');
        $('#login_order_error').css('display','block');
        $('#auth_error').css('display','block');

		$('#hitler').val('Неверные данные').css({color: '#c00'});
		$('#kaput').val('Пароль?').css({color: '#c00'});
    }
}

function loadOblast(first)
{
	//alert(first);
    showImgLoader();
    $('#oblast').html('');
    $('#region').html('');
    $('#dservice').html('');
    $('#delivery').html('');
    $('#payment').html('');
    $('#user').html('');

    var httpURL = '/ajorder/operation/oblast/';
    //alert(httpURL);
    $.post(httpURL, {pay:first}, reOblast, "json");
}

function reOblast(data)
{
	//alert(data);
    removeImgLoader();

    var stop = data['stop'];
    if (!(data=checkStatus(data))) {
        return;
    }
    $('#oblast').attr('innerHTML',data.html);
    if((data['count']==1 || data['load']==1) && stop != 1) {
        loadRegion(data['id']);
    }
    lastAnchor();
}

function loadRegion(oblast)
{
    showImgLoader();
    $('#region').html('');
    $('#dservice').html('');
    $('#delivery').html('');
    $('#payment').html('');
    $('#user').html('');

    var httpURL = '/ajorder/operation/region/';
    $.post(httpURL, {oblast:oblast}, reRegion, "json");
}

function reRegion(data)
{
    removeImgLoader();
    if (!(data=checkStatus(data))) {
        return;
    }
    $('#region').attr('innerHTML',data.html);
    if(data['count']==1 || data['load']==1) {
        loadDelivery(data['id']);
    }
    lastAnchor();
}

var parse_basket = 0;
function resetForm()
{
    $('#order_user_surname').hide();
    $('#order_user_name').hide();
    $('#order_user_tel_code').hide();
    $('#order_user_email').hide();
    $('#order_user_address_delivery').hide();
    $('#order_user_house').hide();
    $('#order_user_flat').hide();
    ////////////////////////////////////////////////////////////////
    $('#order_user_surname_who').hide();
    $('#order_user_name_who').hide();
    $('#order_user_tel_code_who').hide();
    $('#order_user_email_who').hide();
    $('#order_user_address_delivery_who').hide();
    $('#order_user_house_who').hide();
    $('#order_user_flat_who').hide();
    ////////////////////////////////////////////////////////////////
    $('#order_user_surname_anyone').hide();
    $('#order_user_name_anyone').hide();
    $('#order_user_tel_code_anyone').hide();
    $('#order_user_email_anyone').hide();
    $('#order_user_address_delivery_anyone').hide();
    $('#order_user_house_anyone').hide();
    $('#order_user_flat_anyone').hide();
    ////////////////////////////////////////////////////////////////
    $('#order_user_index').hide();
    $('#order_user_oblast').hide();
    $('#order_user_city').hide();
    $('#order_user_floor').hide();
    $('#order_user_floor_who').hide();
    $('#order_user_floor_anyone').hide();
}

var validator=new Validator();
function sendOrderForm(my)
{

	var id = null;
	//console.dir(my);
	//return false;
    resetForm();
	//my.submit();
    if ('undefined'!=typeof(my.surname) && (my.surname.value == "" || my.surname.value=='Фамилия')) {
    	alert('Укажите фамилию');
        //$('#order_user_surname').show();
        return false;
    }

    if('undefined'!=typeof(my.name) && (my.name.value == "" || my.name.value=='Имя')) {
    	alert('Укажите имя');return false;
        $('#order_user_name').show();
        return false;
    }

    //if ('undefined'!=typeof(my.tel_code) && (my.tel_code.value=="" || isNaN(parseInt(my.tel_code.value)) || my.tel.value == "" || my.tel.value=='фЕМЕЖПО' || !validator.isDigits(my.tel_code.value) || my.tel_code.length<3 || !validator.isDigits(my.tel.value) || my.tel.length<3)) {

    if('undefined'!=typeof(my.tel_code) && (my.tel_code.value.length<0)) {
    	alert('Укажите телефонный код');return false;
        $('#order_user_tel_code').show();
        return false;
    }
	if('undefined'!=typeof(my.tel) && (my.tel.value.length<0)) {
    	alert('Укажите номер телефона');return false;
        $('#order_user_tel').show();
        return false;
    }
	if (!validator.isDigits(my.tel_code.value) || my.tel_code.value.length<3) {
		alert('Неверно введен телефонный код');return false;
        $('#order_user_tel_code').show();
        return false;
	}
	if (!validator.isDigits(my.tel.value) || my.tel.value.length<5 || my.tel.value.length>7) {
		alert('Неверно введен номер телефона');return false;
        $('#order_user_tel').show();
        return false;
	}

    if('undefined'!=typeof(my.email) && (my.email.value.length < 6 || my.email.value.indexOf('@') < 1 || my.email.value.indexOf(".") < 1)) {
    	alert('Укажите email');return false;
        $('#order_user_email').show();
        return false;
    }

    if('undefined'!=typeof(my.index) && (my.index.value=="" || my.index.value=='Индекс')) {
    	alert('Укажите индекс');return false;
    	$('#order_user_index').show();
        return false;
    }
    /*
    if('undefined'!=typeof(my.oblast) && (my.oblast.value=="")) {
    $('#order_user_oblast').show();
    return false;
    }*/

    if('undefined'!=typeof(my.city) && (my.city.value=="" || my.city.value=='Город')) {
    alert('Укажите город');return false;
    $('#order_user_city').show();
    return false;
    }

    if ('undefined'!=typeof(my.address_delivery) && (my.address_delivery.value=="" || my.address_delivery.value=='Название улицы, проспекта')) {
    	alert('Укажите улицу');return false;
        $('#order_user_address_delivery').show();
        return false;
    }

    if ('undefined'!=typeof(my.house) && (my.house.value=="" || my.house.value=='Дом / корпус')) {
    	alert('Укажите номер дома');return false;
        $('#order_user_house').show();
        return false;
    }

    //alert('Here all right');return false;
	//alert('thats ok');
    //return;
	my.submit();
}

function showPresentForm(id, idout, idnew)
{
    var my = document.getElementById(id);

    if(my && my.checked) {
        createCookie('present_form', 1);
        $('#kiev').hide();
        $('#kiev_present').show();
    } else {
        createCookie('present_form', 0);
        $('#kiev').show();
        $('#kiev_present').hide();
    }

    var idnew = $('#'+idnew);
    var idout = $('#'+idout);
    idnew.attr('innerHTML',idout.attr('innerHTML'));

    if(my && my.checked) {
        idnew.attr('innerHTML',idout.attr('innerHTML'));
    } else {
        idnew.attr('innerHTML', '&nbsp;');
    }
}

var removeImgLoad = 0;
/*function showImgLoader()
{
removeImgLoad = 1;
$("body").append("<div id='TB_load'><img src='/img/js/loadingAnimation.gif' onload='is_showImgLoader();'/></div>");//add loader to the page
$('#TB_load').show();//show loader
}
*/

function showImgLoader()
{
    removeImgLoad = 1;
    $(document.body).append("<div id='TB_load' style='position:absolute;'><img src='/img/js/loadingAnimation.gif' onload='is_showImgLoader();'/></div>");//add loader to the page

    var loader = $('#TB_load');
    var left = Math.round($(window).width() / 2) - Math.round(loader.width() / 2);
    var top = Math.round($(window).height() / 2) - Math.round(loader.height() / 2);

    loader.css('left',left);
    loader.css('top', top);
    loader.css('z-index',1003);
    loader.show();//show loader
}


function is_showImgLoader()
{
    if(removeImgLoad==0) {
        removeImgLoader();
    }
}

function removeImgLoader()
{
    removeImgLoad = 0;
    $("#TB_load").remove();
}

function zakazat(caption, url, imageGroup, urlADD)
{
    window.focus();
    if (url) {
        tb_show(caption, url, imageGroup);
    }
    if (urlADD) {
        addItem(urlADD);
    }
}

function compare(url)
{
    window.focus();
    if (url) {
        open_window(url,1000,800);
    }
}
function showAmountMessage(message) {
    $('#amountMessText').html(message);

    var dialog = $('#amountMess').show();
    var left = Math.round($("#cart-window").width() / 2) - Math.round(130);
    var top = Math.round($("#cart-window").height() / 2) - Math.round(dialog.height() / 2);

    dialog.css('z-index',1002);
    dialog.css('left',left);
    dialog.css('top', top);
}
function hideAmountMessage() {
    $('#amountMess').hide();
}
