/**
 * @author Andrius Jukna <endris.j[at]gmail.com>
 * @license: feel free to use it, but keep this credits!	
 */

var patternNumber		= /^([0-9])+$/;
var patternPhone		= /^\+?([0-9\-\s])+$/;
var patternPhoneE		= /^\+?([0-9\-\s])*$/;
var patternPhoneStrong	= /^\+([0-9]{11})+$/;
var patternName			= /^([a-zA-ZąĄčČęĘėĖįĮšŠųŲūŪžŽ_\.\-\s])+$/;
var patternNameE		= /^([a-zA-ZąĄčČęĘėĖįĮšŠųŲūŪžŽ_\.\-\s])*$/;
var patternUsername		= /^.+$/;
var patternEmail 		= /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var patternEmailE		= /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})*$/;
var patternPassword	= /^.+$/;


$(document).ready(function() {
	$('.delete').bind('click', function() {
		return confirm('Ar tikrai norite ištrinti?');
	})
	
	if(typeof markErrors == 'function') markErrors();
	if(typeof callThenLoaded_Login == 'function') callThenLoaded_Login();
	if(typeof callThenLoaded_Print == 'function') callThenLoaded_Print();
	if(typeof callThenLoaded_Logged == 'function') callThenLoaded_Logged();
	if(typeof callThenLoaded_ClosedZoneMenu == 'function') callThenLoaded_ClosedZoneMenu();
	if(typeof callThenLoaded_CtrlSpecific == 'function') callThenLoaded_CtrlSpecific();
	if(typeof callThenLoaded_weatherInit == 'function') callThenLoaded_weatherInit();
	if(typeof callThenLoaded_Poll == 'function') callThenLoaded_Poll();
	if(typeof callThenLoaded_userRegistration == 'function') callThenLoaded_userRegistration();
	if(typeof callThenLoaded_SendFriend == 'function') callThenLoaded_SendFriend();
	if(typeof callThenLoaded_SendFriendFooter == 'function') callThenLoaded_SendFriendFooter();
	if(typeof callThenLoaded_Search == 'function') callThenLoaded_Search();
	if(typeof callThenLoaded_Reminders == 'function') callThenLoaded_Reminders();
	if(typeof callThenLoaded_NewestUsers == 'function') callThenLoaded_NewestUsers();
});

function submitSendFriend(recommend) {
	if(!checkElement('SendFriendSenderName', patternName)) return false;
	if(!checkElement('SendFriendReceiverEmail1', patternEmail)) return false;
	
    // AJAX form submit
    $.post(base+"__/send_friend/send/", {
            comment				: oComment.val(),
            sender_name 		: oSenderName.val(),
            sender_email		: oSenderEmail.val(),
            receiver_email_1	: oReceiver1.val(),
            receiver_email_2	: oReceiver2.val(),
            receiver_email_3	: oReceiver3.val(),
            link                : here
        },
        function(res) {
        	$('#recommendLoading').hide();
        	$('#recommendBtn').show();
        	if(recommend) {
        		window.recommend_PP.disablePp();
    		} else {
    			window.PP.disablePp();
    		}
        });
        
    $('#recommendBtn').hide();
    $('#recommendLoading').show();
    return false;
}

function checkElement(id, pattern) {
	var item = $('#'+id);
	item.removeClass('error');
	if(!isValidByPattern(item.val(), pattern)) {
        item.focus();
        item.addClass('error');
        return false;
    }
    return true;
}

function isValidByPattern(value, pattern) {
    value = value.replace(/^\s+/, '');
    value = value.replace(/\s+$/, '');
    if(pattern.test(value))
        return true;
    return false;
}
function isNotEmpty(value) {
    value = value.replace(/^\s+/, '');
    value = value.replace(/\s+$/, '');
    if(value && value != "undefined")
        return true;
    return false;
}

function isUniqueUsername(element) {
	if('' == oUN.val()) {
		oUN.css('width', fieldUNwidth);
		oUN.addClass('error');
		$('#UserUsernameYes').hide();
		$('#UserUsernameNo').show();
		return ;
	}
	$.post(base+"__/user_registration/is_un_unique/",
			{ 
				username	: element.val(),
				user_id		: $('#UserId').val()
			},
			function(res) {
				var o = eval("("+res+")");
				if(0 == o.code) {
					oUN.css('width', fieldUNwidth);
					oUN.removeClass('error');
					$('#UserUsernameNo').hide();
					$('#UserUsernameMsg').hide();
					$('#UserUsernameYes').show();
					isUNOK = true;
				} else {
					oUN.css('width', fieldUNwidth);
					oUN.addClass('error');
					$('#UserUsernameYes').hide();
					$('#UserUsernameNo').show();
					$('#UserUsernameMsg').html(o.message);
					$('#UserUsernameMsg').show();
					isUNOK = false;
				}
		});
	
	return true;
}

function removeBlock(id) {
    $('#'+id).remove();
    return false;
};

function inc(filename)
{
	var head = document.getElementsByTagName('head').item(0);
	script = document.createElement('script');
	script.src = filename;
	script.type = 'text/javascript';
	head.appendChild(script)
}


/* CHAT POPUP */
function createPopup(url, window_name, height, width) {
	window.open(
            url,
            window_name,
            'channelmode=no,directories=no,fullscreen=no,height='+height+',left=100,location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,titlebar=yes,toolbar=no,top=100,width='+width
        );
    
    
    return false;
}
/* END. chat popup */

/* SMOOTH SCROLL */

jQuery.fn.extend({
  scrollTo : function(speed, easing, leaveSpace) {
    return this.each(function() {
      var targetOffset = $(this).offset().top - leaveSpace;
      $('html,body').animate({scrollTop: targetOffset}, speed, easing);
    });
  }
});
/* END. smooth scroll */

/* PRINT */
var Print = {
    disabled: [],
    added: [],

    addPrintButton: function() {
        var out = '<div class="printButtons">';
            out += '<button type="button" onclick="window.print();">';
            out += 'Spausdinti';
            out += '</button>';
            out += ' ';
            out += '<button type="button" onclick="Print.swithToNormalLayout();">';
            out += 'Grįžti';
            out += '</button>';
            out += '</div>';
        $(out).prependTo('body');
    },

    removePrintButton: function() {
        $('div.printButtons').remove();
    },

    swithToPrintLayout: function() { 
        var Print = this;
        var s = $('style');
        var l = $('link[@rel=stylesheet]');
        var a = [];

        $.each(s, function(i,n){a.push(n);});
        $.each(l, function(i,n){a.push(n);});
        $.each(a, function(i, n) {
            var media = $(n).attr('media');
            if(media) switch(media.toLowerCase()) {
                case 'print':
	                var o = n.cloneNode(false);
	                o.media = 'screen';
	                Print.added.push(o);
	                n.parentNode.insertBefore(o, n);
	                break;
                
                default:
	                if(!n.disabled) {
	                    n.disabled = true;
	                    Print.disabled.push(n);
	                }
	                break;
            }
        });
    
        Print.addPrintButton();
    },
    
    swithToNormalLayout: function(){
        var Print = this;
        $.each(Print.disabled, function(i,n){n.disabled = false;});
        $.each(Print.added, function(i,n){
            n.disabled = true;
            n.parentNode.removeChild(n);
        });

        Print.disabled = [];
        Print.added = [];
        Print.removePrintButton();
    }
};
/* END. print */
