// JavaScript Document
function property(url,name)
{
	var newwindow;
	var iMyWidth;
	var iMyHeight;
	iMyWidth = (window.screen.width/2) - (900 + 10);
	iMyHeight = (window.screen.height/2) - (900 + 50);
	newwindow=window.open(url,name,'height=510,width=764,left=200,top=100,screenX=764,screenY=510,toolbar=no,menubar=no,scrollbars=yes,location=no,directories=no,resizable=no,status=yes');
	if (window.focus) {newwindow.focus()}
}

function openWinCentered(loc, winname, widthh, heightt) {
    var tp = Math.ceil((screen.height - heightt) / 2);
    var lf = Math.ceil((screen.width - widthh) / 2);
//    if (params.length > 0)
//        params = "," + params;
    var win = window.open(loc, winname, "width=" + widthh + ",height=" + heightt + ",top=" + tp + ",left=" + lf + "location=no,status=no,toolbar=no,menubar=no,resizable=no,scrollbars=no");
    win.focus();
    return win;
}
function openDialog( widthh, heightt, id)
{
    var tp = Math.ceil((screen.height-300 - heightt) / 2);
    var lf = Math.ceil((screen.width - widthh) / 2);
 
    var tab=document.getElementById(id);
	tab.style.display="block";
	tab.style.left=lf;
	tab.style.top=tp;
}

function show_window(win)
{
    e = window.event;
    var x = e.clientX;
    var y = e.clientY;	
//document.getElementById("m").innerHTML=document.write(x+"  {}  "+y);
        var d=null;
        d = document.getElementById(win);
		d.style.display="block";
		d.style.position="absolute";
		d.style.zIndex="2000";
		d.width=200;
		d.height=200;
		d.style.left=x;
		d.style.top=y;
}

function hide_window(id)
{
document.getElementById(id).style.display="none";	
}


// numbersonly
function numbersonly(myfield, e, dec){
		var key;
		var keychar;

		if (window.event)
		   key = window.event.keyCode;
		else if (e)
		   key = e.which;
		else
		   return true;
		keychar = String.fromCharCode(key);

		if ((key==null) || (key==0) || (key==8) || 
		    (key==9) || (key==13) || (key==27) )
		   return true;

		else if ((("0123456789").indexOf(keychar) > -1))
		   return true;

		else if (dec && (keychar == "-"))
		   {
		   myfield.form.elements[dec].focus();
		   return false;
		   }
		else
		   return false;
	}
function decision(message, url){
	if(confirm(message)) location.href = url;
}


// print

function doClick()
{
window.print();
}





function checkAlluncheckAll(field)
{
for (i = 0; i < field.length; i++)
if(field[i].checked == true) 
field[i].checked = false;
else 
field[i].checked = true
}
function checkAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}

function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
	field[i].checked = false ;
}


function additional(mySelect,name,key) {
      myIndex = mySelect.selectedIndex;
      myValue = mySelect.options[myIndex].value;
      var obj = (document.getElementById)? document.getElementById(name) : eval("document.all[name]");
      if (myValue == key){
		obj.style.display="";
	} else {
		obj.style.display="none";
	}
}



function transparent(element)
{
	if(/MSIE (5\.5|6).+Win/.test(navigator.userAgent)) 
	{
		var src = element.src;
		element.src = config.spacerPath; 
		if (src) element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
	}
}

function showPic(pic, width, height)
{ 
	sDesrc = "width=" + width + ", height=" + height + ", status=no, toolbar=no, menubar=no, scrollbars=no";
	win = window.open("gallery_image.php?pic=" + pic, "", sDesrc);
}

function showVideo(video_id, width, height)
{ 
	sDesrc = "width=" + width + ", height=" + height + ", status=no, toolbar=no, menubar=no, scrollbars=no";
	win = window.open("video.php?video_id=" + video_id + "&width=" + width + "&height=" + height, "", sDesrc);
}

var send = function(link,filename)
{
 	var dataToSend = document.getElementById('calendar_y').value + "." + document.getElementById('calendar_m').value;
 	var ajax = new httpAjaxRequest(); 
	if(ajax)
	{  
		ajax.prepareHash({date:dataToSend}); 
		ajax.open("GET", filename);
		ajax.send();
		ajax.getData();
		ajax.onreadystatechange = function()
		{ 
			data = ajax.getResult();
			document.getElementById("calendar_div").innerHTML = data.calendar; 
		}  
	}
 	else 
 	{
 		window.location = link + document.getElementById('calendar_y').value + "." + document.getElementById('calendar_m').value;
 	}
}




function show_player(filename)
{
	var width=300;
	var height=220;
	document.write("<embed name='player' type='application/x-mplayer2' pluginspage='http://microsoft.com/windows/mediaplayer/en/download/' width='"+width+"' height='"+height+"' showcontrols='true' autostart='false' src='"+filename+"'></embed>");
}
function show_player2(filename)
{
	var width=540;
	var height=380;
	document.write("<embed name='player' type='application/x-mplayer2' pluginspage='http://microsoft.com/windows/mediaplayer/en/download/' width='"+width+"' height='"+height+"' showcontrols='true' autostart='false' src='"+filename+"'></embed>");
}
function playerWindow(filename)
{
	var width=500;
	var height=285;
	
	var myBars = 'directories=no,location=no,menubar=no,status=no,titlebar=no,toolbar=no'; 
	var myOptions = 'scrollbars=yes,width=500,height=285,resizeable=yes'; 
	var myFeatures = myBars + ',' + myOptions; 
	var wnd = open('','',myFeatures);
	wnd.document.write("<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><title>title</title><style type='text/css'><!-- body,td,th {	font-size: 12px;} body { background-color: #000000; margin-left: 0px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; } --></style></head><body><embed name='player' type='application/x-mplayer2' pluginspage='http://microsoft.com/windows/mediaplayer/en/download/' width='500' height='285' showcontrols='true' autostart='true' src='"+filename+"'></embed></body></html>");
}


function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

function sendByPost(hiddenField,myvalue)
{
var myvalue;
var myHiddenfield = document.getElementById(hiddenfield);
myHiddenfield.value = myvalue;
document.form.submit();
}

function mylink(url,param)
{
var url;
var params;
http.open("GET",url+"?"+params, true);
}

function showhidediv(name){
	var obj = (document.getElementById)? document.getElementById(name) : eval("document.all[name]");
	if (obj.style.display=="none"){
		obj.style.display="";
	} else {
		obj.style.display="none";
	}
}
function showdiv(name){
	var obj = (document.getElementById)? document.getElementById(name) : eval("document.all[name]");
	obj.style.display="";
}
function hidediv(name){
	var obj = (document.getElementById)? document.getElementById(name) : eval("document.all[name]");
	obj.style.display="none";
}








/* PRODUCT FUNCTIONS  ------------------------------------------------------- */
var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
function switchRegion(rid, img)
{
    $('table.pregion').hide();
    $('li.ril').removeClass('here');
    $('#ri-'+rid).show();
    $('#ril-'+rid).addClass('here');
    $('.bigpic-img').hide();
    if ($('span.bpr-'+rid).length > 0) {
        $('span.bpr-'+rid).css('display', 'inline-block');
    } else {
        $('img.bpr-'+rid).show();
    }
}
function addToCart(pid)
{
    cart_add(pid, $('#ca-size').val(), $('#ca-qty').val());
    return false;
}

function productSave()
{
    if (!$('#sa-email').val()) {
        showMessage('Введите Ваш e-mail!');
        return false;
    }
    $.getJSON(
        '/my/save/', 
        $('#sa').serialize(),
        function(data) {
            if (data['code']) {
                $('#sa').fadeOut();
            } else {
                showMessage(data['msgs']);
            }
        }
    );
}


/* CART MANAGEMENT  --------------------------------------------------------- */
function cart_repaint(data)
{
    var num = 0;
    var sum = 0;
    for(var k in data)  {
        num += 1*data[k]['qty'];
        sum += 1*data[k]['qty']*data[k]['price'];
    }
    
    // if cart is empty - hide-show controls
    if (!num) {
        $('.korzina,.bf').hide();
        $('#cart-empty-msg').show();
    }
    return;
}

function cart_add(pid, size, qty)
{
    if (!pid) {
        showMessage('Ошибка! Не указан товар.', 'error');
        return false;
    }
    if (!size) {
        showMessage('Ошибка! Не выбран размер.', 'error');
        return false;
    }
    if (!qty) {
        showMessage('Ошибка! Не указано количество.', 'error');
        return false;
    }
    $.getJSON(
        '/cart/add/', 
        {'pid': pid, 'size': size, 'qty': qty},
        function () {
            location.href = '/cart/';
        }
    );
}

function cart_update(pid, size, qty)
{
    if (!pid) {
        showMessage('Ошибка! Не указан товар.', 'error');
        return false;
    }
    if (!size) {
        showMessage('Ошибка! Не выбран размер.', 'error');
        alert("Ошибка! Не выбран размер.");
        return false;
    }
    if (!qty) {
        showMessage('Ошибка! Не указано количество.', 'error');
        return false;
    }
    $.getJSON(
        '/cart/update/', 
        {'pid': pid, 'size': size, 'qty': qty},
        cart_repaint
    );
}

function cart_remove(pid, size)
{
    if (!pid) {
        showMessage('Ошибка! Не указан товар.', 'error');
        return false;
    }
    if (!size) {
        showMessage('Ошибка! Не выбран размер.', 'error');
        alert("Ошибка! Не выбран размер.");
        return false;
    }
    $.getJSON(
        '/cart/remove/', 
        {'pid': pid, 'size': size},
        cart_repaint
    );
    
    $('#item-'+pid+'-'+size).remove();
}


/* ORDER MANAGEMENT  -------------------------------------------------------- */
function order_update_total()
{
    var total = subtotal;
    
    // repaint delivery
    var el = $('input[name=id_deliveries]');
    var delivery = undefined;
    for(var i=0; i < el.length; i++) {
        var row = el.get(i);
        if (row.checked) {
            delivery = deliveries[row.value];
        }
    }
    if (delivery) {
        var delivery_price = delivery['price'];
        total += delivery_price;
        total = Math.round(100*total) / 100;
    }
    if (coupon != $('#coupon').val()) {
        coupon = $('#coupon').val();
        coupon_value = 0;
        if (coupon != '') {
            $.getJSON(
                '/order/coupon/?coupon='+coupon, 
                function(data) {
                    if (data['code']) {
                        data['value'] = data['value']*1.00;
                        msg = '';
                        if (data['value']) {
                            msg += 'Скидка на '+data['value']+' '+(data['type'] == 'fixed' ? 'у.е.' : '%');
                            if (data['type'] == 'fixed') {
                                coupon_value = data['value'];
                            } else {
                                coupon_value = subtotal*data['value']/100;
                            }
                            coupon_value = Math.round(100*coupon_value)/100;
                            if (data['notes']) {
                                msg += '<br/>';
                            }
                        }
                        if (data['notes']) {
                            msg += '<strong>'+data['notes']+'</strong>';
                        }
                        $('#coupon_info').html(msg);
                    } else {
                        $('#coupon_info').html(data['msgs'][0]);
                    }
                }
            );
        } else {
            $('#coupon_info').html('');
        }
    }
    total -= coupon_value;
    total = Math.round(100*total)/100;
    if (!(total > 0)) {
        total = '0.00';
    }
    
    $('#total').html(total);
}


function addProductListener(pid) {
	
	email = $('#listenerEmail').val();
	
	if (!pid) {
		showMessage('Ошибка! Не указан товар.', 'error');
		return false;
	}
	 
	if (!email) {
		showMessage('Ошибка! Не указан e-mail.', 'error');
		return false;
	}
	 
	$.getJSON(
			'/product/listener/', 
	        {'id_products': pid, 'email': email},
	        function (data) {
	        	type = data['code'] ? 'ok' : 'error';
        		showMessage(data['msgs'], type);
	        }
	);
	
	return false;
}

function setupShadowbox() {
	 Shadowbox.setup("a.thickbox", {
	        gallery:        "mustang",
	        continuous:     true,
	        counterType:    "skip"
	 });
}



/**
 * Forgot password
 */
function forgot_submit()
{
    $.getJSON(
        '/forgot/', 
        {
            'login': $('#forgot-form').find('input[@name=login]').val()
        }, 
        function(data) {
            if (data['code']) {
              alert("Письмо с данными отправлено на e-mail, указанный при регистрации.");
              dialog_close('dialog-forgot');
            } else {
                alert(data['msgs'].join("\n"));
            }
        }
    );
    
    return false;
}


/* SIGN UP FORM  ------------------------------------------------------------ */
var code_re = new RegExp("^[-a-z0-9]*$");
function signup_check_login()
{
    var e_login = $('#signup_form').find('input[@name=code]').val();
    if (e_login == '') {
        $('#login_check').html('');
        return;
    }
    
    // check for letters
    if (!code_re.test(e_login)) {
        $('#signup_form').find('input[@name=code]').val('');
        return alert('В коде можно использовать только строчные латинские буквы, цифры и символ "-".');
    }
    
    $.getJSON(
        '/signup/check_login/', 
        {'login': e_login},
        function (data) {
            var e_login_check = $('#login_check');
            if (data) {
                e_login_check.css('color', '#090');
                e_login_check.html('свободен');
            } else {
                e_login_check.css('color', '#C00');
                e_login_check.html('занят');
            }
        }
    );
}
var pwd_re = new RegExp("^[-a-zA-Z0-9`~!@#\$%\^&*()_+=]*$");
function signup_check_pwd() 
{
    var str_text = ['короткий', 'слабый', 'нормальный', 'сильный'];
    var str_color = ['#C00', '#C00', '#999', '#090'];
    
    var s_login = $('#signup_form').find('input[@name=code]').val();
    var s_password = $('#signup_form').find('input[@name=password]').val();
    
    // check for letters
    if (!pwd_re.test(s_password)) {
        $('#signup_form').find('input[@name=password]').val('');
        return alert('В пароле можно использовать только латинские буквы, цифры и символы.');;
    }
    
    var str = passwordStrength(s_password, s_login);
    
    $('#pwd_check')
        .css('color', str_color[str])
        .html(str_text[str]);
}




/* DIALOG CONTROL ------------------------------------------------------- */
function dialog_show(id, callback)
{
    $('#'+id).fadeIn('slow', callback);
}
function dialog_close(id, callback)
{
    $('#'+id).fadeOut('fast', callback);
}


/* HELPERS -------------------------------------------------------------- */
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

var lastMsg = 1;
function showMessage(msgs, type) {
    lastMsg++;
    if (type == 'ok') {
        title = 'Сообщение';
        mclass = 'msgs_ok';
    } else {
        title = 'Ошибка';
        mclass = 'msgs';
    }
    
    // hack
    title = '';
    
    if (!(msgs instanceof Array)) {
        msgs = [msgs];
    }
    var mid = 'msgs-'+lastMsg;
    var messages = $('<div></div>');
    for(i=0; i<msgs.length; i++) {
        messages.append(msgs[i]);
        if ((i+1) < msgs.length) {
            messages.append($('<hr/>'));
        }
    }
    var m = $('<div style="display:none;"><div></div><div>')
        .attr('class', mclass)
        .attr('id', mid)
        .append(messages);
    $('body').append(m);
    
    tb_show(title, '#TB_inline?height=100&width=300&inlineId='+mid, false);
}


function checkFormSubmitEnter(event) {
	if ((event.keyCode==10) || (event.keyCode==13)) {
		return true
	}
	return false;
}

function formSubmitEnter(event) {
	if (checkFormSubmitEnter(event)) {
		event.target.form.submit();
	}
}


function textCounter(field,cntfield,maxlimit) {
	if (field.value.length > maxlimit) {
		field.value = field.value.substring(0, maxlimit);
	}else{
		cntfield.innerHTML = maxlimit - field.value.length;
	}
}

