var App = App || {};

$(document).ready(function(){
    $(".tooltip").each(function(){
        $(this).hover(function(){
            $(this).children(".tooltip-hover").toggle();
        });
    });
    if($('#bcenter > div').size() > 1){
        setInterval( 'slideSwitchBcenter()', 7000 );  
    }
    
    if($('#subscribers-form').length){
        App.form.initValidation('subscribers-form');
        $('#subscribers-form').submit(function(){
            return App.form.validateForm('subscribers-form');
        });
    }
    if($('#cardholders').length){
        App.form.initValidation('cardholders');
        $('#cardholders').submit(function(){
            return App.form.validateForm('cardholders');
        });
    }
    if($('#school_cardholders_form').length){
        App.form.initValidation('school_cardholders_form');
        $('#school_cardholders_form').submit(function(){
            return App.form.validateForm('school_cardholders_form');         
        });
    }
    $('#city').change(function(){
        $.ajax({
            type: 'GET',
            url: $('#url').val()+ '&ajax=true',
            data: 'city='+$('#city').val(),
            dataType: 'json',
            success: function(data){
                $('#school').empty();
                for(var i in data){
                    if(data[i].id){
                        $('#school').append('<option value='+data[i].id+'>'+data[i].name+'</option>');
                    }
                }
            }
                                     
        }); 
    });
    
    $('#school').one('focus',function(){
        if(i != 1){
            $.ajax({
                type: 'GET',
                url: $('#url').val()+ '&ajax=true',
                data: 'city=0',
                dataType: 'json',
                success: function(data){
                    var schools = new Array();
                    for(var i in data){
                        if(data[i].id){    
                            schools.push([data[i].name, data[i].id]);
                        }
                    }
                    $('#school').autocomplete(schools,{
                        max: 20,
                        minChars: 3,
                        matchContains: true

                    });
                    $("#school").result(function(event, data, formatted) {
                        $("#school_value").val(data[1]);
                    });
                }

            });
            var i = 1;
        }
    });
         
        
        
        
});
function slideSwitchBcenter() {
    var $active = $('#bcenter > div.active');
    if ( $active.length == 0 ) $active = $('#bcenter > div:first');
    if ($active.next().length){
        $active.hide();
        $active.next().show();
        var $next = $active.next();
    }else{
        $active.hide();
        $('#bcenter > div:first').show();
        var $next = $('#bcenter > div:first');
    }
    $active.addClass('last-active');
    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
}
    
function verify(strPassword, id){

    var nUpperCount = strPassword.replace(/[^A-Z]/g, "").length;
    var nLowerCount = strPassword.replace(/[^a-z]/g,"").length;
    var nLowerUpperCount = nUpperCount + nLowerCount;
    var nNumberCount = strPassword.replace(/[^0-9]/g, "").length;
    var nCharacterCount = strPassword.replace(/[^!@#$%^&*?_~]/g, "").length;

    var strenght = 0;
    if (strPassword.length <= 4 && strPassword.length > 0) {
        strenght += 5;
    } else {
        if (strPassword.length >= 8) {
            strenght += 25;
        } else {
            if (strPassword.length > 0) {
                strenght += 10;
            }
        }
    }

    if (strPassword.length == nLowerCount && strPassword.length !=0) {
        strenght += 10;
    } else {
        if (nLowerUpperCount != 0) {
            strenght += 20;
        }
    }

    if (nNumberCount >= 3) {
        strenght += 20;
    } else {
        if (nNumberCount >= 1) {
            strenght += 10;
        }
    }

    if (nCharacterCount > 1) {
        strenght += 25;
    } else {
        if (nCharacterCount == 1) {
            strenght += 10;
        }
    }

    if (nNumberCount > 0 && nLowerCount > 0 && nUpperCount > 0 && nCharacterCount > 0) {
        strenght += 5;
    } else {
        if (nCharacterCount > 0 && nNumberCount > 0 && nLowerUpperCount > 0) {
            strenght += 3;
        } else {
            if (nNumberCount > 0 && nLowerUpperCount > 0) {
                strenght += 2;
            }
        }
    }
    document.getElementById(id).innerHTML = '<b>' + Math.round(strenght*100/95) + "%</b>";
    var color = Math.round(strenght*200/95);
    document.getElementById(id).style.color = 'rgb('+(200 - color)+','+color+',0)';
}
function load (scr, width, height) {
	var flashtag = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="' + width + '" height="' + height + '" id="flash">'
                        +'<param name="allowScriptAccess" value="sameDomain" />'
                        +'<param name="allowFullScreen" value="false" />' 
                        +'<param name="movie" value="' + scr + '" /><param name="menu" value="false" /><param name="quality" value="high" />'
                        +'<embed src="' + scr + '" menu="false" quality="high" width="' + width + '" height="' + height + '" name="flash" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> '
                        +'</object>';
	document.write(flashtag);
}

function slideSwitchBcenter() {
    var $active = $('#bcenter > div.active');
    if ( $active.length == 0 ) $active = $('#bcenter > div:first');
    if ($active.next().length){
        $active.hide();
        $active.next().show();
        var $next = $active.next();
    }else{
        $active.hide();
        $('#bcenter > div:first').show();
        var $next = $('#bcenter > div:first');
    }
    $active.addClass('last-active');
    $next.css({
        opacity: 0.0
    })
    .addClass('active')
    .animate({
        opacity: 1.0
    }, 1000, function() {
        $active.removeClass('active last-active');
    });
}

function getErrorText(element){
    var text = element.prev().text()
    text = text.replace(":", "");
    text = text.replace("*", "");
    text = $.trim(text);
    return text+", ";
}

App.form = {
    initValidation: function(name){
        $('#'+name+' input[rel="tel"]').val("86*******");
        $('#'+name+' input[rel="tel"]').focus(function(){
            if($(this).val() == "86*******"){
                $(this).val("8");		
            }	
        });
        $('#'+name+' input[rel="tel"]').blur(function(){
            if( ($(this).val() == "") || ($(this).val() == "8") ){
                $(this).val("86*******");		
            }	
        });	
    },

    validateForm: function(name){
        var errors = 0;
        var errorFields = "";
        $('#'+name+'-response').html('');
        $("#"+name+" *[data-req]").each(function(){
            $(this).removeClass('error');
            if ( $(this).attr('type') == 'checkbox'  && $(this).is(':checked') ){	
                $(this).parent().css('background-color', ''); 
            }
        });
        $("#"+name+" *[data-req]").each(function(){
            if ($(this).val() == ''){
                errors++;
                $(this).addClass('error');
                errorFields += getErrorText($(this));
            }
            if ( $(this).attr('type') == 'checkbox'  && !($(this).is(':checked'))){	
                errors++;
                errorFields += "nesutikote su taisyklėmis, ";
                $(this).parent().css('background-color', '#EFCECE'); 
            }
            if ($(this).attr('type') == 'radio' && $('#'+name+' input[name="'+$(this).attr('name')+'"]').is(':checked') ==  false ){
                errors++;
                errorFields += getErrorText($(this));
                $(this).addClass('error');  
            }
            if ($(this).is('select') &&  $(this).val() == false  ){
                errors++;
                errorFields += getErrorText($(this));
                $(this).addClass('error'); 
            }
            if ($(this).attr('rel') == 'email' && !App.form.isValidEmail($(this).val()) && $(this).val() != ""){
                errors++;
                errorFields += getErrorText($(this));
                $(this).addClass('error'); 
            }
        });
	$("#"+name+" input[rel='words']").each(function(){
	    if ( !App.form.isWords($(this).val()) || $(this).val() == ""){
                errors++;
                if( errorFields.indexOf(getErrorText($(this))) == -1 ){
                    errorFields += getErrorText($(this));
                }
                $(this).addClass('error');
            }else{
		$(this).removeClass('error');
	    }
	});
	$("#"+name+" input[rel='tel']").each(function(){
            if($(this).attr("data-req") == "required"){
                console.log($(this).val());
                if($(this).val() == "86*******"){
                    errors++;
                    errorFields += getErrorText($(this));
                    $(this).addClass('error');
                }else{
                    if( !App.form.isPhoneNumber($(this).val()) ){
                        errors++;
                        if( errorFields.indexOf(getErrorText($(this))) == -1 ){
                            errorFields += getErrorText($(this));
                        }
                        $(this).addClass('error');
                    }else{
                        $(this).removeClass('error');
                    }
                }
            }else{
                if( !App.form.isPhoneNumber($(this).val()) ){
                    errors++;
                    if( errorFields.indexOf(getErrorText($(this))) == -1 ){
                        errorFields += getErrorText($(this));
                    }
                    $(this).addClass('error');
                }else{
                    $(this).removeClass('error');
                }
            }
	});
        if (errors > 0){
            var index = errorFields.lastIndexOf(",");
            errorFields = errorFields.substring(0, index)+".";
            $('#'+name+'-response').html('Neteisingai užpildyti laukai: '+errorFields);
            return false;
        }else{
	    $("#"+name+" input[rel='tel']").each(function(){	        
		if( ($(this).val() == "86*******") || ($(this).val() == "8") ){
		    $(this).val("");
	        }
	    });
            return true;
        }
    },
    limitLength: function (obj, maxlength){
        if ($(obj).val().length > maxlength){
            $(obj).val($(obj).val().substring(0, maxlength));
        }
    },
    numbersOnly:function(e){
        var unicode=e.charCode? e.charCode : e.keyCode

        if (unicode!=8){ //if the key isn't the backspace key (which we should allow)
            if (unicode<48||unicode>57) //if not a number
            {
                e.preventDefault();
                return false; //disable key press
            }
        }
    },
    wordsOnly: function(e){
        var allowedLetters = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnmĄČĘĖĮŠŲŪŽąčęėįšųūž";
        var unicode=e.charCode? e.charCode : e.keyCode
        var letter = String.fromCharCode(unicode);
        if (unicode!=8 && unicode !=9){
            if ( allowedLetters.indexOf(letter) == -1 ) 
            {
                e.preventDefault();
                return false; //disable key press
            }
        }
    },
    isValidEmail: function(emailAddress){
        var emailPattern = /^[a-zA-Z0-9\+._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
        return emailPattern.test(emailAddress);
    },
    isPhoneNumber: function(number){
	var phonePattern = /^[8][0-9]{8}$/;
	var testResult = phonePattern.test(number);
	var isPlaceholder = (number == "86*******") ? true : false;
        return (testResult || isPlaceholder) ? true : false;
    },
    isWords: function(text){
        var i;

        for (i = 0; i < text.length; i++){

            var c = text.charAt(i);
            if (((c > "0") && (c < "9"))) return false;

        }
        return true;
    },
    sendEmail: function(name){
        if (App.form.validateForm(name)){
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: ROOT_URL+'?sendform=post&ajax=true',
                data: $("#"+name).serialize(),
                success: function(data) {
                if (data.result == true){
                    $("#"+name+"-response").html(data.msg);
                    $("#"+name).hide();
                }else{
                    $("#"+name).show();
                    $("#"+name+"-response").html(data.msg);
                    }
                },
                error:function (xhr, ajaxOptions, thrownError){
                    $("#"+name+"-response").html(thrownError);
                }
            });
        }
    }
};

