var ajaxInWork = false;
var ajaxError = false;
var additionalEmail = "";

join_btn = new Image();
join_btn.src = "/images/join_btn.gif";
join_btn_hl = new Image();
join_btn_hl.src = "/images/join_btn_hl.gif";

$(document).ready(function() {

    $('.user_menu span').toggle(function() { 
        $('.user_menu').animate({
            top:0
        }, 500, function() {
            $('.user_arrow').removeClass('down').addClass('up');
        });
    }, function() {
        $('.user_menu').animate({
            top:-167
        }, 500, function() {
            $('.user_arrow').removeClass('up').addClass('down');
        });
    });

    // Signin
    $('.btn-signin').click(function() { 
        $.blockUI({ 
            theme: false,
			draggable: true,
			css: { backgroundColor: '#ffffff',
			       color: '#494949',
			       padding: '30px 40px',
			       border: '1px solid #acacac',
			       borderBottom: '1px solid #999999',
			       top:  ($(window).height() - 500) /2 + 'px', 
                   left: ($(window).width() - 400) /2 + 'px',
			       width: '300px' },
            title: 'Join',
            message: $('#signinDialogue')
        });
			$('.blockOverlay').attr('title','Click to unblock').click($.unblockUI);
			$('.esc').click($.unblockUI);
			$.blockUI.defaults.css = {};
    });

    // Tabs
	$(function() {

		//When page loads...
		$(".tab_content").hide(); //Hide all content
		$("ul.tabs li:first").addClass("active").show(); //Activate first tab
		$(".tab_content:first").show(); //Show first tab content

		//On Click Event
		$("ul.tabs li").click(function() {

			$("ul.tabs li").removeClass("active"); //Remove any "active" class
			$(this).addClass("active"); //Add "active" class to selected tab
			$(".tab_content").hide(); //Hide all tab content

			var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
			$(activeTab).fadeIn(); //Fade in the active ID content
			return false;
		});

	});
	
	// In the News
    $('.newsArticle').toggle(function() {
        var id = $(this).attr('id');
        $.ajax({
            type: 'GET',
            url: '/dindex.php?press=getnewstext',
            data: { id: id },
            success: function(message) {
                        $('#news-content-' + id).append(message);
                    },
            error: function() {
                        alert('Sumpin\' broke');
                    }
        });
    },function() {
        var id = $(this).attr('id');
        $('#news-content-' + id).empty();
    });
    
    // Press
    $('.pressArticle').toggle(function() {
        var id = $(this).attr('id');
        $.ajax({
            type: 'GET',
            url: '/dindex.php?press=getpresstext',
            data: { id: id },
            success: function(message) {
                        $('#press-content-' + id).append(message);
                    },
            error: function() {
                        alert('Sumpin\' broke');
                    }
        });
    },function() {
        var id = $(this).attr('id');
        $('#press-content-' + id).empty();
    });

	// Help
	$('.help_item').click(function(e) {
		e.stopPropagation;
		var item = $(this).attr('href');
		alert(item);
		$(item).toggle();
	});

});

function validateJoin() {
    var emailObj = $('#join-email');
    if (emailObj.val() == '') {
        alert('Enter Email Address.');
        emailObj.focus();
        return false;
    }
    else if (!checkEmailAddress(emailObj.val())) {
        alert('Email Address is invalid.');
        emailObj.focus();
        return false;
    }
    
    if (!$('#iam2').attr('checked') && !$('#iam3').attr('checked') && !$('#iam4').attr('checked')) {
        alert('Select Role.');
        return false;
    }
    
    return true;
}

/* Registration */
function registerValidateReg() {
    $('#fa-register').dialog('open');
    registerFillState();
}

function registerValidtateProceed() {
    $('input.ui-state-error').removeClass('ui-state-error');
    $('select.ui-state-error').removeClass('ui-state-error');

    //Set the role id
    role_id = 2;
    
    //The hash value
    var sHash = $('#hash').val();
    
    var fNameObj = $('#first_name');
    var fNameVal = trim(fNameObj.val());
    if (fNameVal == '') {
        registerShowProceedErr('First Name is required.', fNameObj);
        return false;
    }
    
    var lNameObj = $('#last_name');
    var lNameVal = trim(lNameObj.val());
    if (lNameVal == '') {
        registerShowProceedErr('Last Name is required.', lNameObj);
        return false;
    }
    
    var nNameObj = $('#nick_name');
    var nNameVal = trim(nNameObj.val());
    if (nNameVal == '') {
        registerShowProceedErr('Nickname is required.', nNameObj);
        return false;
    }
    else
    {
        ajaxError = false;
        $.ajax({
            url: 'index.php?user=check_nick_name'
          , type: 'POST'
          , dataType: 'json'
          , data: 
            {
                nick_name: nNameVal 
              , first_name: $('#first_name').val()
              , last_name: $('#last_name').val()
            }
          , success: function(response)
            {
                if (response != '')
                {
                    if (response.code != 0) 
                    {
                        registerShowProceedErr(response.message, nNameObj);
                        ajaxError = true;
                        return false;
                    }
                }
            }
          , async: false
        });

        if (ajaxError) return false;
    }

    var passwordObj = $('#password');
    var passwordVal = trim(passwordObj.val());
    if (passwordVal == '') {
        registerShowProceedErr('Password is required.', passwordObj);
        return false;
    }
    else {
        var result = checkPassword(passwordVal);
        if (result != '')
        {
            registerShowProceedErr(result, passwordObj);
            return false;
        }
    }

    var confirmObj = $('#confirm');
    var confirmVal = trim(confirmObj.val());
    if (confirmVal == '') {
        registerShowProceedErr('Confirm Password is required.', confirmObj);
        return false;
    }

    if (passwordVal != confirmVal) {
        registerShowProceedErr('Passwords do not match.', confirmObj);
        return false;
    }

    var emailObj = $('#signup_email');
    var emailVal = trim(emailObj.val());
    if (emailVal == '') {
        registerShowProceedErr('Email is required.', emailObj);
        return false;
    }
    else
    {
        ajaxError = false;
        $.ajax({
            url: '/dindex.php?user=check_email'
          , type: 'POST'
          , dataType: 'json'
          , data: 
            {
                email: emailVal 
              , continueEmail: ''
              , roleID: role_id
            }
          , success: function(response)
            {
                if (response != '')
                {
                    if (response.code != 0) 
                    {
                        registerShowProceedErr(response.message, emailObj);
                        ajaxError = true;
                        return false;
                    }
                }
            }
          , async: false
        });

        if (ajaxError) return false;

        ajaxError = false;
        $.ajax({
            url: '/dindex.php?user=check_blocked_domain'
          , type: 'POST'
          , dataType: 'json'
          , data: 
            {
                email: emailVal 
            }
          , success: function(response)
            {
                if (response != '')
                {
                    if (response.code != 0) 
                    {
                        additionalEmail = emailVal;
                        registerShowProceedErr(response.message, emailObj);
                        ajaxError = true;
                        return false;
                    }
                }
            }
          , async: false
        });

        if (ajaxError) return false;
    }
    
    countryObj = $('#country_id');
    countryVal = trim(countryObj.val());
    if (countryVal == '') {
        registerShowProceedErr('Country is required.', countryObj);
        return false;
    }
    
    stateAbbrObj = $('#state-abbr');
    stateAbbrVal = trim(stateAbbrObj.val());
    if (stateAbbrObj.is(':visible') && stateAbbrVal == '') {
        registerShowProceedErr('State or Province is required.', stateAbbrObj);
        return false;
    }
    
    stateNameObj = $('#state-name');
    stateNameVal = trim(stateNameObj.val());
    if (stateNameObj.is(':visible') && stateNameVal == '') {
        registerShowProceedErr('State or Province is required.', stateNameObj);
        return false;
    }
    
    genderObj = $('#gender');
    genderVal = trim(genderObj.val());
    if (genderObj.is(':visible') && genderVal == '') {
        registerShowProceedErr('Gender is required.', genderObj);
        return false;
    }
    
    securityQObj = $('#security_question');
    securityQVal = trim(securityQObj.val());
    if (securityQVal == '') {
        registerShowProceedErr('Security Question is required.', securityQObj);
        return false;
    }
    
    securityAObj = $('#security_answer');
    securityAVal = trim(securityAObj.val());
    if (securityAVal == '') {
        registerShowProceedErr('Security Question is required.', securityAObj);
        return false;
    }
    
    if (!$('#agree').attr('checked')) {
        registerShowProceedErr('You should read terms of use and check checkbox.', $('#terms'));
        return false;
    }
    
    if (ajaxInWork) {
        return false;
    }
    
    ajaxInWork = true;
    
    $('#validateTips').html('<img src="/images/icons/ico_exclam_gray.gif" alt="" />&nbsp;&nbsp;Please provide name and password info.');
    $('.ui-dialog-buttonpane').append('<div class="reg-loading" style="text-align: right; padding-top: 10px; width: 350px;"><img src="/images/ja/small-eeeeee.gif" alt="Checking..." width="16" height="11" /></div>');
    
    $.post(
        '/dindex.php?user=save_member',
        {
            role_id: role_id,
            email: emailVal,
            signup_email: emailVal,
            additional_email: additionalEmail,
            first_name: fNameVal,
            last_name: lNameVal,
            nick_name: nNameVal,
            password: passwordVal,
            country_id: countryVal,
            state_abbr: stateAbbrObj.is(':visible') ? stateAbbrVal : '',
            state_name: stateNameObj.is(':visible') ? stateNameVal : '',
            gender: genderVal,
            security_question_id: securityQVal,
            security_answer: securityAVal,
            hash: sHash
        },
        function(response){
            if (response.code == 0) {
            	document.location.href = 'app/';
            } else {
                registerShowProceedErr(response.message);
                $('.reg-loading').remove();
            }
            ajaxInWork = false;
        },
        'json'
    );
}

function registerValidtateSend() {
    $('input.ui-state-error').removeClass('ui-state-error');
    $('select.ui-state-error').removeClass('ui-state-error');
    
    fNameObj = $('#your_first_name');
    fNameVal = trim(fNameObj.val());
    if (fNameVal == '') {
        registerShowSendErr('Your First Name is required.', fNameObj);
        return false;
    }
    
    lNameObj = $('#your_last_name');
    lNameVal = trim(lNameObj.val());
    if (lNameVal == '') {
        registerShowSendErr('Your Last Name is required.', lNameObj);
        return false;
    }

    fFANameObj = $('#fa_first_name');
    fFANameVal = trim(fFANameObj.val());
    if (fFANameVal == '') {
        registerShowSendErr('FA\'s First Name is required.', fFANameObj);
        return false;
    }
    
    lFANameObj = $('#fa_last_name');
    lFANameVal = trim(lFANameObj.val());
    if (lFANameVal == '') {
        registerShowSendErr('FA\'s Last Name is required.', lFANameObj);
        return false;
    }
    
    emailsObj = $('#emails');
    emailsVal = trim(emailsObj.val());
    if (emailsVal == '') {
        registerShowSendErr('FA\'s Email Addresses is required.', emailsObj);
        return false;
    }
    
    var emailsArr = emailsVal.split(',');
    for (i = 0; i < emailsArr.length; i++) {
        email = trim(emailsArr[i]);
        if (email == '') {
            continue;
        }
        
        if (!checkEmailAddress(email)) {
            registerShowSendErr('FA\'s Email Address <strong>'+strip_tags(email)+'</strong> is invalid.', emailsObj);
            return false;
        }
    }
    
    subjObj = $('#subject');
    subjVal = trim(subjObj.val());
    if (subjVal == '') {
        registerShowSendErr('Subject is required.', subjObj);
        return false;
    }
    
    msgObj = $('#message');
    msgVal = trim(msgObj.val());
    if (msgVal == '') {
        registerShowSendErr('Message is required.', msgObj);
        return false;
    }
    
    if (ajaxInWork) {
        return false;
    }
    
    ajaxInWork = true;
    
    $('#validateTips-inv-rec').html('<img src="images/icons/ico_exclam_gray.gif" alt="" align="left" style="margin-right: 10px;" />You must be invited by a Financial Advisor in order to join LinkedFA');
    $('.ui-dialog-buttonpane').append('<div class="reg-loading" style="text-align: right; padding-top: 10px; width: 220px;"><img src="/images/ja/small-eeeeee.gif" alt="Sending..." width="16" height="11" /></div>');
    
    $.post(
        '/dindex.php?user=save_invite',
        {
            role_id: $('#role_3').attr('checked') ? 3 : 4,
            email: $('#join_email').val(),
            first_name: fNameVal,
            last_name: lNameVal,
            fa_first_name: fFANameVal,
            fa_last_name: lFANameVal,
            emails: emailsVal,
            subject: subjVal,
            message: msgVal
        },
        function(response){
            $('.reg-loading').remove();
            $('#fa-register,#inv-rec-register').dialog('close');
            if (response.code == 0) {
                $('#validateTips-apply').html('<img src="/images/icons/ico_apply_gray.gif" alt="" align="left" style="margin-right: 10px;" />' + response.message);
                $('#apply-register').dialog('open');
            } else {
                $('#validateTips-error').html('<img src="/images/icons/ico_block_gray.gif" alt="" align="left" style="margin-right: 10px;" />' + response.message);
                $('#error-register').dialog('open');
            }
            
            ajaxInWork = false;
        },
        'json'
    );
}

function registerHideRegErr() {
    if (ajaxInWork) {
        return;
    }
    
    /*if ($('#email-role-error').is(':visible')) {
        $('#email-role-error').fadeOut(function(){
        });
    }*/
}

function registerShowProceedErr(err, o) {
    $('#validateTips').html('<img src="/images/icons/ico_block_gray.gif" alt="" align="left" style="margin-right: 10px;" />' + err);
    if (o) {
        o.addClass('ui-state-error').focus();
    }
}
function registerShowSendErr(err, o) {
    $('#validateTips-inv-rec').html('<img src="/images/icons/ico_block_gray.gif" alt="" align="left" style="margin-right: 10px;" />' + err);
    if (o) {
        o.addClass('ui-state-error').focus();
    }
}
function registerFillState() {
    $('#state-label').append('<img src="/images/ja/small-eeeeee.gif" alt="Loading.." width="16" height="11" id="state-load" style="padding-left: 20px;" />');
    $.post('/pub/ajax/select_states_by_country.php',
        {country_id: $('#country_id').val(), empty_val: 'Select one'},
        function(response){
            $('#state-load').remove();
            
            var length = 0;
            var options = '';
            $.each(response, function(key, val) {
                options += '<option value="' + key + '">' + val + '</option>';
                length++;
            });
            
            if (length > 1) {
                $('#state-name').hide();
                $('#state-abbr').html(options).show();
            } else {
                $('#state-abbr').hide();
                $('#state-name').empty().show();
            }
        }, 'json'
    );
}
/* End Registration */


/*
function newsShow(id) {
    if (ajaxInWork) {return false;}
    var nObj = $('#news-content-'+id);
    ajaxInWork = true;
    nObj.append('<div style="position: relative;"><div style="position: absolute;"><img src="../images/ja/small-ffffff.gif" style="padding-top: 5px;" id="news-wait" /></div></div>');
    $.get('index.php?press=getnewstext', {id: id}, function(data){
        $('#news-wait').remove();
        nObj.html(data);
        document.location.href = '#'+id;
        ajaxInWork = false;
    });
    return false;
}
function pressShow(id) {
    if (ajaxInWork) {return false;}
    var nObj = $('#press-content-'+id);
    ajaxInWork = true;
    nObj.append('<div style="position: relative;"><div style="position: absolute;"><img src="../images/ja/small-ffffff.gif" style="padding-top: 5px;" id="press-wait" /></div></div>');
    $.get('index.php?press=getpresstext', {id: id}, function(data){
        $('#press-wait').remove();
        nObj.html(data);
        document.location.href = '#'+id;
        ajaxInWork = false;
    });
    return false;
}
*/

/* End News */
