$(document).ready(function(){
 /*   $('.bodyContent h2').dropShadow(
        {
                left: 0,
                top: 1,
                blur: 1,
                opacity: .5,
                color: "black",
                swap: false
        }
    ); */
     $('.scroll-pane').jScrollPane({
        scrollbarWidth: 7,
        showArrows: false,
        dragMinHeight: 116
    });
    
     $("#UserUser, #UserPass").live("keydown", function(event){
        if(event.keyCode == 13){
             $('#loginPop').submit();
        }
    });
    
     $("#password").live("keydown", function(event){
        if(event.keyCode == 13){
             document.theLogin.submit();
        }
    });
    
    $("#ImportPassword").live("keydown", function(event){
        if(event.keyCode == 13){
             getContacts();
        }
    });
    
      $("#username").live("keydown", function(event){
        if(event.keyCode == 13){
             document.theLogin.submit();
        }
    });
  
  $("#UserMailingCountryId").change(function(event){
        getStateOptions($("#UserMailingCountryId").val(), 'UserMailingStateId');
        $('#UserMailingStateId').focus();
    });
    
   $("#UserBillingCountryId").change(function(event){
        getStateOptions($("#UserBillingCountryId").val(), 'UserBillingStateId');
        $('#UserBillingStateId').focus();
    });
  
    $('a[rel*=facebox]').facebox();  
    $("#inviteesList").tablesorter();
    
});

function getStateOptions(countryID, fieldID){
    $.get('/sc/getStates/'+countryID+'/1', function(html){
            $('#'+fieldID).html(html);
    }); 
}

var canClose = true; 

function formValidate(type){

	var magicString = $.trim($('#'+type).val());
	closeCorrect(type);

    switch(type){
        default:
        break;

        case 'firstname':
			if(magicString.length <= 0){
				showError(type, 'You must enter your first name!');
			}
			else{
				closeError(type);
				showCorrect(type);
			}
        break;

        case 'lastname':
			if(magicString.length <= 0){
				showError(type, 'You must enter your last name!');
			}
			else{
				closeError(type);
				showCorrect(type);
			}
        break;
    }
}

function showError(type, msg){
    $('#'+type+'Error').show();
    $('#'+type+'Error').html(msg);
}

function closeError(type){
    $('#'+type+'Error').hide();
}

function emailValidate(email){
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if(reg.test(email) == false) {
        return false;
    }
    else{
        return true;
    }
}

function download(){
	$("#downloadLink").hide();
	changeStep('1');
}

function verify(){
	var username = $('#username').val();
	var password = $('#password').val();
}

function clearInput(inputID){
    var defaultValue = $('#'+inputID).get(0).defaultValue;
    var currentValue = $('#'+inputID).val();
    if(defaultValue == currentValue){
        $('#'+inputID).val('');
    }
}

function insertDefaultValue(inputID){
    var defaultValue = $('#'+inputID).get(0).defaultValue;
    var currentValue = $('#'+inputID).val();
    if(currentValue == ''){
        $('#'+inputID).val(defaultValue);
    }
}

function authUser(username, password){
	$.post("http://clicketysplit.com/ajax.php", {action: 'login', username: username, password: password}, function(response){
		if(response){
			if(response == 'true'){
				return true;
			}
			else{
				return false;
			}
		}	
		else{
			return false;
		}
	});
}

function userVerification(){
	var username = $("#username").val();
	var password = $("#password").val();
	var check = authUser(username, password);
	if(check == true){
		// successfully authenticated
		changeStep('2');
	}
	else{
		// please try again
		$("#validationError").show();
	}
}

function changeStep(num){
	$(".step").hide();
	$("#step"+num).show();
}

function hideIt(id){
    $(id).hide();
}

function showIt(id){
    $(id).show();
}

function showSubNav(){
    if($('.subNav').is(':hidden')){
        closeSubNav();
        $('.subNav').show();
    }
}

function closeSubNav(){
    if(canClose == true){
        $('.subNav').hide();
    }
}

function unCheckMe(id){
    $('.checkers').attr('checked', false);
    $('#'+id).attr('checked', true);
}

function disableClosing(){
    canClose = false;
}

function enableClosing(){
    canClose = true;
}

function clearInput(id){
    $("#"+id).val('');
}

function toggleSetting(name, status){
    $('#'+name+'On').toggle();
    $('#'+name+'Off').toggle();
    $('#'+name+'Panel').toggle();
    $('#'+name+'Panel2').toggle();
    
    switch(status){
        case 'generalOn':
            setCookie('general', 'on', 9999);
        break;
        case 'generalOff':
            setCookie('general', 'off', 9999);
        break;
        case 'mailingOn':
            setCookie('mailing', 'on', 9999);
        break;
        case 'mailingOff':
            setCookie('mailing', 'off', 9999);
        break;
        case 'billingOn':
            setCookie('billing', 'on', 9999);
        break;
        case 'billingOff':
            setCookie('billing', 'off', 9999);
        break;
        case 'passwordOn':
            setCookie('password', 'on', 9999);
        break;
        case 'passwordOff':
            setCookie('password', 'off', 9999);
        break;
    }
}

function inviteToggle(){
    hideTip();
    $('#importer').toggle();
}

function importStepsToggle(){
    $('#step1').toggle(); 
    $('#step2').toggle();
}

function getContacts(){
    var email = $('#ImportEmail').val();
    var password = $('#ImportPassword').val();
    var method = $('#ImportMethod').val();
    
    if(email == '' || password == '' || method == ''){
        alert('You must complete all fields');
    }
    else{
        $.getJSON('/sc/getContacts/'+email+'/'+password+'/'+method, function(json){
            showContacts(json);
        });
    }
}

function showContacts(data){
    $('#step1').hide();
    $('#step2').show();
    var html = '';
    
    for(var x in data){
        html = html + '<input type="checkbox" value="'+data[x].email+'" name="'+data[x].email+'" class="contactCheckBox" /> <label for="'+data[x].email+'">' + data[x].name +' ('+ data[x].email +')</label><br />';
    }
    
    $('#contacts').html(html);
}

function importContacts(){
    var contactList = new Array();
    
    $(".contactCheckBox:checked").each(
      function() {
        contactList.push($(this).val());
      }
    );
    
    var sendTo = contactList.join(', ');
    backStep();
    inviteToggle();
    $('#recipients').val(sendTo);
}

function backStep(){
    $('#step1').show();
    $('#step2').hide();
}

function checkAll(){ 
    $(".contactCheckBox").attr('checked', true); 
}

function deselectAll(){ 
    $(".contactCheckBox").attr('checked', false); 
}

function showTip(){
    $('#importTip').show();    
}

function hideTip(){
    $('#importTip').hide(); 
}

function invite(){
    var sendTo = $('#recipients').val();
    var msg = $('#message').val();
    
    if(sendTo != ''){
        $("#loader").toggle();
        $("#inviteButton").toggle(); 
        
        $.getJSON('/sc/invite/'+sendTo+'/'+msg+'/', function(response){
            if(parseInt(response.code) > 0){
                // error?
                if(response.message == 'Unauthorized'){
                    window.location = "http://clicketysplit.com/sc/login";
                }
                else if(response.message != ''){
                    alert(response.message);
                }
                else{
                     $.facebox($('#inviteError').html());
                }
            }
            else{
                // clear the fields the message was sent.
                $('#recipients').val('');
                $('#message').val('');
                $.facebox($('#inviteComplete').html());
            }
            
            $("#loader").toggle();
            $("#inviteButton").toggle(); 
        });
    }
    else{
        $.facebox($('#inviteInComplete').html());
    }
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}


function acceptAgreement(){
        jQuery(document).trigger('close.facebox');
        window.location = "http://clicketysplit.com/csd/clickety-setup.exe";
        
}

function acceptAgreement2(){
        jQuery(document).trigger('close.facebox');
        window.location = "http://clicketysplit.com/sc/upgrade";
}

function closeAgreement(){
        jQuery(document).trigger('close.facebox');
}

function showInvitees(){
    $.getJSON('/sc/getInviteesList/', function(json){
        if(json.invites != null){
            var html = '';
            for(x in json.invites){
                html += '<tr><td>'+json.invites[x].recipient_email+'</td><td>'+json.invites[x].status+'</td><td>'+json.invites[x].date_invited+'</td></tr>';
            }
            $('#inviteesList tbody').html(html);
            $("#inviteesList").trigger("update"); 
            var sorting = [[0,0]]; 
            // sort on the first column 
            $("#inviteesList").trigger("sorton",[sorting]);
            $("#inviteesList").tablesorterPager({container: $("#pageroo"), positionFixed: false});
            $("#invitees").show(); 
            //$.facebox($('#invitees').html());
        }
        else if(json.message == 'Unauthorized'){
            window.location = "http://clicketysplit.com/sc/login";
        }
        else{
            // no invites have been sent
            alert('You have not sent any invites.');
        }
    });  
}

function closeInvitees(){
    $("#invitees").hide();  
}

function shortURL(destinationURL){
    $.getJSON('http://clicketysplit.com/api2/service/url_shorten.json?url='+destinationURL, function(response){
        alert(response);
    });
}