$(document).ready(function(){
    initLoginForm();
    initRegisterForm();
    initCalculator();
    initSave();
    initOk();
    areaDivFeetTB = document.getElementById('tb_areafeet');
    
    /*$('.write').click(function(){
        if ($('#tb_areafeet').val() != $('#tb_areafeet').attr('title')){
            $('#area').html($('#tb_areafeet').val());
            $('#area_in').val($('#tb_areafeet').val());
        }  
        
        return false;       
    });*/
    
    $('input[name="calc_name"]').click(function(){
        if ($(this).val() == $(this).attr('title')){
            $(this).val('');
            $(this).css('color','#333333');
        }
    });
    
    $('#overlay H2').click(function(){
        if ($(this).attr('class') == 'close'){
            $(this).addClass('open').removeClass('close');
            $('#overlay UL').slideDown('normal');
        } else {
            $(this).addClass('close').removeClass('open');
            $('#overlay UL').slideUp('normal');        
        }
    });
    
    $('input[name="calc_name"]').blur(function(){
        if ($(this).val() == ''){
            $(this).val($(this).attr('title'));
            $(this).css('color','#eeeeee');
        }
    });
    
    $('.center A.save').click(function(){
        if (isVisible($('#save'))){
            $('#save').submit();
        } else {
            $('.right-box').slideDown('normal');
            $('#error-save').html('Enter name of your calculation in the field below and click the <span>Save Calculation</span> button to save it.');
            $('#error-save').css('color','#898989');
            $('#error-save').show(); 
            $('input[name="calc_name"]').css('color','#eeeeee');           
            $('#save').slideDown('normal');
            document.getElementById('save').reset();
        }
    
    });
    
    $('#overlay A.del').click(function(){
            if (confirm('You are about to delete this calculation\r\n "Cancel" to stop, "OK" to delete.')){
                $('#overlay').load($('#calculator').attr('action') , {ajax:1, del:$(this).attr('rel'), activ:$('#overlay H2').attr('class')},
                    function(){
                            if ($('#overlay LI').size() == '0'){
                                $('#overlay').hide();
                            }
                    });
            }
    });

    Gload();
    
});
function isVisible(obj) { return (obj.css('display') == 'block'); } 

function hidestr() {
    $('#map DIV[dir="ltr"]').hide();
}

function initLoginForm(){
	$('#login').submit(function(){
		var form = $(this);
		var formData = $(this).serialize();
		var error = '';
        $('#error').hide();
        $.ajax({
			type: 'POST', url: form.attr('action'), data: formData, 
			success: function ( responseData ){
                if(!Process(responseData)){
                    $('#error').html('ERROR: Invalid username or password');
					$('#error').css('color','red');
                    $('#error').show();
				} else{
                    window.location.href = $('#redirect').val();
				}
			}
		});		
		return false;
	});
}

function initCalculator(){
	$('#calculator').submit(function(){
		var form = $(this);
		var formData = $(this).serialize();
		var error = '';
        $('#error').hide();
        $.ajax({
			type: 'POST', url: form.attr('action'), data: formData, 
			success: function ( responseData ){
				if((error = ProcessCalc(responseData)) != ''){
                    $('#error').html(error);
					$('#error').css('color','red');
                    $('#error').show();
				} else{
                    var list = responseData.split(':');
                    var data = list[1].split(';');
					$('#bwd').html(data[0]);
                    if (!$('#not-visible').attr('checked')){
                        $('#not-required').hide();
                        $('#ip').parent().show();
                        $('#ip').html(data[1]);
                    } else {
                        $('#not-required').show();
                        $('#ip').parent().hide();
                    }
                    $('#pf').html(data[2]);
                    $('#cost').html(data[3]);
                    $('#price').html(data[4]);
                    $('#sp').html(data[5]);
                    $('.calculate-weekly-dosage').hide();
                    $('.price-button').show();
                    $('.my-price').slideDown(1000);
				}
			}
		});		
		return false;
	});
}

function initSave(){
	$('#save').submit(function(){
		var form = $(this);
		var formData = $(this).serialize();
		var error = '';
        $('#error-save').hide();
        $.ajax({
			type: 'POST', url: form.attr('action'), data: formData, 
			success: function ( responseData ){
				if((error = ProcessCalc(responseData)) != ''){
                    $('#error-save').html(error);
					$('#error-save').css('color','#CC0000');
                    $('#error-save').show();
				} else{
                    document.getElementById('save').reset();
                    form.slideUp('normal');
                    $('#saved').html('Your calculation is saved');
                    $('#saved').css('color','#90C343');
                    $('#saved').slideDown('normal');
                    $('#overlay').load($('#calculator').attr('action') , {ajax:1, activ:$('#overlay H2').attr('class')});
                    $('#overlay').show();
                    setTimeout('$("#saved").slideUp("normal");', 10000);
                    setTimeout('hideBox();', 10000);
				}
			}
		});		
		return false;
	});
}

function initOk(){
	$('#my_price').submit(function(){
		var form = $(this);
		var formData = $(this).serialize();
		var error = '';
        $('#error').hide();
        $.ajax({
			type: 'POST', url: form.attr('action'), data: formData, 
			success: function ( responseData ){
				if((error = ProcessCalc(responseData)) != ''){
                    $('#error').html(error);
					$('#error').css('color','#CC0000');
                    $('#error').show();
				} else{
                    var list = responseData.split(':');
                    var data = list[1].split(';');
					$('#cost').html(data[0]);
                    $('.my-cost').show();
                    hidePriceElem();
				}
			}
		});		
		return false;
	});
}

function clickNo(){
    hidePriceElem();
    $('.my-cost').hide();
    return false;
}

function hidePriceElem(){
    if (!isVisible($('.blue-box'))){
        $('.blue-box').slideDown(1000);
    }
    $('.calculate-weekly-dosage').show();
    $('.price-button').hide();
    $('.my-price').slideUp(1000);    
}

function hideBox(){
    if (!isVisible($('#save'))){
        $(".right-box").slideUp("normal");
    }
}

function initRegisterForm(){
	$('#register').submit(function(){
		var form = $(this);
		var formData = $(this).serialize();
		var error = '';
        $('#error').hide();
        $.ajax({
			type: 'POST', url: form.attr('action'), data: formData, 
			success: function ( responseData ){
				if(!ProcessReg(responseData)){
                    $('#error').html(getRegError(responseData));
					$('#error').css('color','red');
                    $('#error').show();
				} else{
					window.location.href = $('#redirect').val();
				}
			}
		});		
		return false;
	});
}

function getRegError(str){
    str = str.substr(4000,700);
    str = str.replace(/\r\n|\r|\n/g,"<br>");
    
    var re = new RegExp('<div id="login_error">.*</div>','m');
    var m = re.exec(str);
    if (m == null) {
        return 'ERROR: Please, fill all required fields';
    } else {
        var s = "";
        for (i = 0; i < m.length; i++) {
          s = s + m[i] + "\n";
        }
        return s.replace("<br>",'');
    }
}


function ProcessReg(str){
    if(str.indexOf('Registration Form') + 1) {
        return false;
    } else {
        return true;
    }  
}

function Process(str){
    if(str.indexOf('ERROR') + 1) {
        return false;
    } else {
        return true;
    }  
}

function ProcessCalc(str){
	list = str.split(':');
    var res = '';
	if(list[0].toLowerCase() != 'done'){
		return list[1];
	} else {
		return res;
	}
}

