var W3CDOM = (document.createElement && document.getElementsByTagName);

function initFileUploads() {
	if (!W3CDOM) return;
	var fakeFileUpload = document.createElement('div');
	fakeFileUpload.className = 'fakefile';
	fakeFileUpload.appendChild(document.createElement('input'));
	var image = document.createElement('img');
	image.src='images/obzor.gif';
	fakeFileUpload.appendChild(image);
	var x = document.getElementsByTagName('input');
	for (var i=0;i<x.length;i++) {
		if (x[i].type != 'file') continue;
		if (x[i].parentNode.className != 'fileinputs') continue;
		x[i].className = 'file hidden';
                x[i].name='ticket_file';
		var clone = fakeFileUpload.cloneNode(true);
		x[i].parentNode.appendChild(clone);
		x[i].relatedElement = clone.getElementsByTagName('input')[0];
		x[i].onchange = x[i].onmouseout = function () {
			this.relatedElement.value = this.value;
		}
	}
}

var cfHeight = {"checkbox": 25, "radio": 25}

/* No need to change anything after this */

var Custom = {
	init: function() {
		var inputs = document.getElementsByTagName("input");
		for(var a = 0; a < inputs.length; a++) {
			if((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled") {
				Custom.initCheckRadio(inputs[a]);
			}
		}
		inputs = document.getElementsByTagName("select");
		for(var a = 0; a < inputs.length; a++) {
			if(inputs[a].className == "styled") {
			    Custom.initSelect(inputs[a]);
			}
		}
	},
	pushed: function() {
		element = this.nextSibling;
		if (element.checked) {
			this.style.backgroundPosition = "0 -" + cfHeight[element.type] * 3 + "px";
                       
		} else {
			this.style.backgroundPosition = "0 -" + cfHeight[element.type] + "px";
		}
	},
	check: function() {
		element = this.nextSibling;
		if(element.checked && element.type == "checkbox") {
			this.style.backgroundPosition = "0 0";
			element.checked = false;
		} else {
			this.style.backgroundPosition = "0 -" + cfHeight[element.type]*2 + "px";
			if(element.type == "radio") {
				group = this.nextSibling.name;
				inputs = document.getElementsByTagName("input");
				for(a = 0; a < inputs.length; a++) {
					if(inputs[a].name == group && inputs[a] != this.nextSibling) {
						inputs[a].previousSibling.style.backgroundPosition = "0 0";
					}
				}
			}
			element.checked = true;
		}
	},
	clear: function() {
		inputs = document.getElementsByTagName("input");
		for(var b = 0; b < inputs.length; b++) {
	        if (inputs[b].className == "styled_")
	        {
    			var _span = inputs[b].previousSibling;
        		_span.style.backgroundPosition = Custom._getBgPos(inputs[b]);
    		}
		}
	},
	choose: function() {
		option = this.getElementsByTagName("option");
		for(var d = 0; d < option.length; d++) {
			if(option[d].selected) {
	           document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
                    if(this.name.indexOf('newAount')!=-1)
                        {
                              $.post('/convert_cart.php', {"action": 'Upd',"newCount": option[d].value,"position" :this.name.replace(/newAount/,'')}, function(msg) {
            $('#cart').html(msg);
            cartSelect = document.getElementsByTagName("select");
		for(var a = 0; a < cartSelect.length; a++) {
			if(cartSelect[a].className == "styled") {
			    Custom.initSelect(cartSelect[a]);
			}
		}


        });
                        }
                                
			}
		}
	},

	
	initSelect: function(obj) {
		var option = obj.getElementsByTagName("option");
		var active = option[0].childNodes[0].nodeValue;
		var textnode = document.createTextNode(active);
		for (var b = 0; b < option.length; b++)
        {
			if (option[b].selected == true)
            {
				textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
			}
		}
		var _span = document.createElement("span");
		_span.className = "select";
		_span.id = "select" + obj.name;
		_span.appendChild(textnode);
		obj.parentNode.insertBefore(_span, obj);
		obj.onchange = Custom.choose;
		obj.className = "styled_";
    },

    
    initCheckRadio: function(obj) {
		var _span = document.createElement("span");
		_span.className = obj.type;
        var _position = Custom._getBgPos(obj);
		_span.style.backgroundPosition = _position;
		obj.parentNode.insertBefore(_span, obj);

        if (!obj.disabled)
        {
            obj.onchange = obj.onclick = Custom.clear;
    		_span.onmousedown = Custom.pushed;
    		_span.onmouseup = Custom.check;
    		document.onmouseup = Custom.clear;
    	}
		obj.className = "styled_";
    },

    _getBgPos: function(obj) {
        var _pos = "0 0";
		if (obj.disabled) {
            _pos = "0 -" + (cfHeight[obj.type] * 4) + "px";
        } else if (obj.checked) {
            _pos = "0 -" + (cfHeight[obj.type] * 2) + "px";
		}
		return _pos;
    }
}


function checkboxCheck (name) {

  if (document.getElementById(name+"_checkbox").checked) {
	document.getElementById(name+"-checkboxDiv").className="checkboxOn";
   }
	else {
	 document.getElementById(name+"-checkboxDiv").className="checkboxOff";
	}
}

function collapseBox(id) {
                $('#message_body'+id).slideToggle(300);
                if($('#message_head'+id).attr('class')=='message_head active')
                    $('#message_head'+id).removeClass('message_head active').addClass('message_head inactive');
                else
                    $('#message_head'+id).removeClass('message_head inactive').addClass('message_head active');
                return false;
	
}

function ChangeImg(elid, link)
{
	if (document.getElementById('0'+link) == null)
		return;

	document.getElementById('0'+link).src='css/btnz/'+elid+'/'+link+'_hilite.png';
	for (i=1; i<6; i++) {
		if(i!=link) {
			if (document.getElementById('0'+i) != null) {
				document.getElementById('0'+i).src='css/btnz/'+elid+'/'+i+'_default.png';
			}
		}
	}
}

function checkActive(elid) {
	for (i=1; i<6; i++) {
		if (document.getElementById("cs-button-" + elid + "-"+i) == null)
			continue;

		if(document.getElementById("cs-button-" + elid + "-"+i).className==("cs-button-" + elid + " cs-active"))
			return i;
	}
}


function refreshUserCp(content)
{
    text=decodeURIComponent(content);
    $('#user-cp-div').html(text);
     $('#login-button').click(function (e) {
		$('#loginForm').modal({opacity:70});

		  return false;
	});
}
function processJson(data) {
   $('#loader-icon').hide();
   if(data=='error')
       $('#error-msg').show();
    else{
        refreshUserCp(data);
       $.modal.close();
       }
    
}
function AddToExp(cat,id)
{
    $.post('/action/changeWaitStat.php', {"action":'add',"g": cat,"id":id}, function(msg) {
   $('#etc_info').html("<br>Товар внесён в лист ожидания.<br/><img style='margin-top:12px;'  src='images/vnesti_inactive.gif'/>");
        });
}
function validate()
{
     $('#loader-icon').show();
}
function addItemtToCart(cat,id,comment)
{
	var options = {
		"action": 'Add',
		"AddGoodsCat": cat, 
		"AddGoodsId": id,
		"AddGoodsAmount":'1'
	};
	if (comment != undefined) {
		options.Comment = comment;
	}
   $.post('/convert_cart.php',
   options,
   function(msg) {
            refreshUserCp(msg.message);
            $.jGrowl('Товар: '+decodeURIComponent(msg.name)+' добавлен в корзину');
        }, "json");
    
}

function AcceptPay(id,oid)
{
   $.post('/acceptPay.php', {"oid": oid}, function(msg) {
   $('#order_code_status'+id).html('<img style="margin: 20px 35px 0 0" src="images/podtverzhdena.gif"/>');
   $('#payment_info_'+id).html('');
   $('#order_status_'+id).html('Статус: <a target="_blank" href="index.php?p=order_stats.php#paid">заказ оплачен</a>');
        });
}
function AcceptReceiving(id,oid)
{
   $.post('/acceptOrder.php', {"oid": oid}, function(msg) {
   $('#payment_info_'+id).html('');
   $('#order_status_'+id).html('Статус: заказ доставлен');
        });
}
function AddSubscribeItem(id)
{
 
var objSel = document.getElementById("subSelect");
if ( objSel.selectedIndex != -1)
$.post('/action/subscribe.php', {"bid": id,"category":objSel.options[objSel.selectedIndex].value}, function(msg) {
   $('div.my_sub_list').html(decodeURIComponent(msg));
   Custom.initSelect(document.getElementById('subSelect'));
        });
        
  


}
function DelSubscribeItem(id,cat_id)
{

$.post('/action/subscribe.php', {"bid": id,"category":cat_id}, function(msg) {
   $('div.my_sub_list').html(decodeURIComponent(msg));
   Custom.initSelect(document.getElementById('subSelect'));
        });
}

function DeleteCartItem(number)
{
      $.post('/convert_cart.php', {"action": 'Upd',"DelNom": number}, function(msg) {
            
            $('#cart').html(msg);
            cartSelect = document.getElementsByTagName("select");
		for(var a = 0; a < cartSelect.length; a++) {
			if(cartSelect[a].className == "styled") {
			    Custom.initSelect(cartSelect[a]);
			}
		}
           
          
             
        });
}
function postTicketComment()
{
    var theme=$("#").val();
}
  function getStarCheckedValue() {
	var radioGrp;
         radioGrp = document.getElementsByName('star2');
           if(!radioGrp)
		return "";
	var radioLength = radioGrp.length;
	if(radioLength == undefined)
		if(radioGrp.checked)
			return radioGrp.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioGrp[i].checked) {
			return radioGrp[i].value;
		}
	}
	return "";



}
function postReview(cat,id)
{
  var msg=$("#REVIEW_TEXT").val();
  if(msg!='')
    $.post('/addReview.php', {"msg": msg, "id": id, "g":cat, "rat":getStarCheckedValue()}, function() {
      $("#REVIEW_TEXT").attr("disabled","disabled");
      $("#rewTit").html('<img src="images/ostavit_otzyv_inactive.gif">');
      $("#rewBlock").css("opacity", "0.4");
      $("#sRewB").html('<img src="images/otzyv_dobavlen03.gif"><div>Ваш отзыва добавлен и будет опубликован после проверки модератором. Благодарим за внимание.</div>');
      });
}
function DeleteTicket(id)
{
      $.post('/delete_t.php', {"ticket_id": id}, function(msg) {
      $('#t_'+id).slideUp('fast');
      });
}
function DelWaitItem(id,cat_id)
{

$.post('/action/changeWaitStat.php', {"action":'delete',"g": cat_id,"id":id}, function(msg) {
   $('div.my_exp_list').html(decodeURIComponent(msg));
        });




}
function addSubscrItem(cat,id)
{

$.post('/action/subscribe.php', {"bid": id,"category":cat}, function() {
   $.jGrowl('Подписка на данный раздел прошла успешно.');
   $("#subCheck").remove();
        });
}
function changeAgBnt()
{
    if($("#ag_checkbox").is(':checked'))
        $("#ag_btn_div").html('<input type="image" src="images/posetit_active.gif"/>');
    else
        $("#ag_btn_div").html('<img src="images/posetit_inactive.gif"/>');
    
}
function logout()
{
    $.ajax({
			url: "/action/logout.php",
			cache: false,
			success: function(html){
				 refreshUserCp(html);
                                 $('#login-button').click(function (e) {
		                 $('#loginForm').modal({opacity:70});
                                 return false;
	                 });
			}
		});
}
    $(document).ready(function() {
        Custom.init();
        Shadowbox.init({counterType:'default',continuous:true,animSequence:'sync'});
        $('#sb-body-inner').live('click', function(){
        Shadowbox.next();
        });
        initFileUploads();
        $('#login-form').ajaxForm({
        beforeSubmit: validate,
        success:   processJson
    });

//validator
var validator = $("#RegForm").validate({
		rules: {
			LName: "required",
			FName: "required",
      		Patronymic: "required",
            Phone: "required",
            country: "required",
            p_index: "required",
            city: "required",
            street: "required",
            house: "required",
			Login: {
				required: true,
				remote: {
                    url: "check_user.php",
                    type: "post"
                }
			},
			Paswd: {
				required: true,
				minlength: 6
			},
			PaswdConfirm: {
				required: true,
				minlength: 6,
				equalTo: "#Paswd"
			},
			email: {
				required: true,
				email: true,
				remote: {
                    url: "check_email.php",
                    type: "post"
                }
			},
			apartment: {
				required: "#private_house_checkbox[checked=false]"
			}
		},
		messages: {
			LName: "Необходимо указать фамилию",
			FName: "Необходимо указать имя",
            Patronymic: "Необходимо указать отчество",
			Login: {
				required: "Необходимо указать логин",
				remote: "Такой логин уже существует "
			},
			Paswd: {
				required: "Необходимо указать пароль",
				minlength: "Пароль должен быть не короче 6 символов"
			},
			PaswdConfirm: {
				required: "Необходимо указать пароль",
				minlength: "Пароль должен быть не короче 6 символов",
				equalTo: "Пароли не соответствуют друг другу"
			},
			email: {
				required: "Необходимо указать email адрес",
				email: "Необходимо указать правильный email адрес",
				remote: "Такой e-mail уже используется"
			},
			Phone: "Необходимо указать телефон",
			country: "Необходимо указать страну",
            p_index: "Необходимо указать индекс",
            city: "Необходимо указать город",
            street: "Необходимо указать улицу",
            house: "Необходимо указать номер дома",
            apartment: "Необходимо указать номер квартиры или указать что у Вас частный дом (отдельное строение)"

		},
		// the errorPlacement has to take the table layout into account
		errorPlacement: function(error, element) {
			if ( element.is(":radio") )
				error.appendTo( element.parent().next().next() );
			else if ( element.is(":checkbox") )
				error.appendTo ( element.next() );
			else
				error.appendTo( element.parent().next() );
		},
		// specifying a submitHandler prevents the default submit, good for the demo
		submitHandler: function() {
			this.submit();
		},
		// set this class to error-labels to indicate valid fields
		success: function(label) {
			// set &nbsp; as text for IE
			label.html("&nbsp;").addClass("checked");
		}
	});

//hide message_body after the first one
	$(".message_list .message_body:gt(0)").hide();


     $(".menu > li").click(function(e){
         switch(e.target.id){
             case "my_details":
                 //change status & style menu
                 $("#my_details").addClass("active");
                 $("#my_sub_list").removeClass("active");
                 $("#my_exp_list").removeClass("active");
                 $("#my_points").removeClass("active");
                 //display selected division, hide others
                 $("div.my_details").css("display", "block");
                 $("div.my_sub_list").css("display", "none");
                 $("div.my_exp_list").css("display", "none");
                 $("div.my_points").css("display", "none");
             break;
             case "my_sub_list":
                 $("#my_details").removeClass("active");
                 $("#my_sub_list").addClass("active");
                 $("#my_exp_list").removeClass("active");
                 $("#my_points").removeClass("active");
                 //display selected division, hide others
                 $("div.my_details").css("display", "none");
                 $("div.my_sub_list").css("display", "block");
                 $("div.my_exp_list").css("display", "none");
                 $("div.my_points").css("display", "none");
             break;
             case "my_exp_list":
               $("#my_details").removeClass("active");
                 $("#my_sub_list").removeClass("active");
                 $("#my_exp_list").addClass("active");
                 $("#my_points").removeClass("active");
                 //display selected division, hide others
                 $("div.my_details").css("display", "none");
                 $("div.my_sub_list").css("display", "none");
                 $("div.my_exp_list").css("display", "block");
                 $("div.my_points").css("display", "none");
             break;
             case "my_points":
                 $("#my_details").removeClass("active");
                 $("#my_sub_list").removeClass("active");
                 $("#my_exp_list").removeClass("active");
                 $("#my_points").addClass("active");
                 //display selected division, hide others
                 $("div.my_details").css("display", "none");
                 $("div.my_sub_list").css("display", "none");
                 $("div.my_exp_list").css("display", "none");
                 $("div.my_points").css("display", "block");
             break;
         }
         //alert(e.target.id);
         return false;
     }); 

    $('#login-button').click(function (e) {
		$('#loginForm').modal({opacity:70});

		  return false;
	});
        
});

function toggleInputDisabled( elementId ) {
	var disabled = $("#" + elementId).attr("disabled");
	if (disabled) {
		$("#" + elementId).css("opacity", "1").removeAttr("disabled");
	} else {
		$("#" + elementId).css("opacity", "0.5").attr("disabled", "disabled").val("");
	}
}
