//-- Setup Global variables
var username;
var account_id;
var domain;
var email;

$(document).ready(function(){

    //-- Set the actions
    $('#sel_locCountry').change(function() {
        loadDropDown('sel_locState', '_country='+$('#sel_locCountry').val());
    });
    $('#sel_locState').change(function() {
        loadDropDown('sel_locCity', '_country='+$('#sel_locCountry').val()+'&_state='+$('#sel_locState').val());
    });
    //-- Load the inital data
    loadDropDown('sel_locCountry');

});

//-- START FUNCTIONS
var structure_data = new Array ();
structure_data['sel_locCountry'] = new Array ();
structure_data['sel_locCountry']['htmlID'] = 'sel_locCountry';
structure_data['sel_locCountry']['htmlDefaultText'] = 'Select a Country';
structure_data['sel_locCountry']['htmlDisableText'] = 'This should never be disabled';
structure_data['sel_locCountry']['xmlListName'] = 'sel_locCountry'; 
structure_data['sel_locCountry']['children'] = new Array('sel_locCountry','sel_locState','sel_locCity'); 

structure_data['sel_locState'] = new Array ();
structure_data['sel_locState']['htmlID'] = 'sel_locState';
structure_data['sel_locState']['htmlDefaultText'] = 'Select a State';
structure_data['sel_locState']['htmlDisableText'] = 'Select a Country first';
structure_data['sel_locState']['xmlListName'] = 'sel_locState';
structure_data['sel_locState']['children'] = new Array('sel_locState','sel_locCity'); 

structure_data['sel_locCity'] = new Array ();
structure_data['sel_locCity']['htmlID'] = 'sel_locCity';
structure_data['sel_locCity']['htmlDefaultText'] = 'Select a City';
structure_data['sel_locCity']['htmlDisableText'] = 'Select a State first';
structure_data['sel_locCity']['xmlListName'] = 'sel_locCity';
structure_data['sel_locCity']['children'] = new Array('sel_locCity'); 

function getAjaxBaseURL()
{
    if ( document.domain.substr(0,8) == '192.168.') {
        baseURL = location.href.match(/(https?:\/\/[^\/]*\/[^\/]*\/?.*)\/.*/)
    } else {
        var urlArray = location.href.match(/(https?:\/\/[^\/]*\/[^\/]*\/?).*/);
    }
    var baseURL = RegExp.$1;
    if (baseURL.substring(baseURL.length-1) != '/')
    {
        baseURL += '/';
    }
    
    return baseURL;
}

function loadDropDown(name, data) {
    disableDropdown(name);
    $('#'+structure_data[name]['htmlID']).html('<option>Loading Data...</option>');
    $.ajax({
        type: "POST",
        url: getAjaxBaseURL(),
        data: 'action=ll&' + data,
        dataType: "xml",
        success: function(xml) {
            $('#'+structure_data[name]['htmlID'])
                .html('<option>'+structure_data[name]['htmlDefaultText']+'</option>');
            $(xml).find("list[name='"+ structure_data[name]['xmlListName'] +"'] option").each(function(){
            $('<option></option>')
                .html($(this).text())
                .val($(this).attr('value'))
                .appendTo('#'+ structure_data[name]['htmlID']);
            }); //close each
            $('#'+name).removeAttr('disabled');
        }
    }); //close $.ajax
}

function disableDropdown(name) {
    var children = structure_data[name]['children'];
    for ( var i in children ) {
        $('#'+structure_data[children[i]]['htmlID'])
            .html('<option>'+structure_data[children[i]]['htmlDisableText']+'</option>');
        $('#'+children[i]).attr('disabled', 'disabled');
    }
}

function enableChild(name) {
    //-- Only enable if a real option is selected
    if ( $('#'+name+' option:selected').val() != $('#'+name+' option:selected').text() ) {
        var children = structure_data[name]['children'];
        $('#'+children[0]).removeAttr('disabled');
    }
}

function addOverlay(id) {
    if ( typeof(id) == "undefined" || id == "") {
        id='overlay';
    }
    id = id.replace('#','');
    
    if ( $('#'+ id).size() == 0 ) {  //-- Only add if an object with this ID does not already exist
        $('body').append('<div id="'+ id +'" style="display: none;"></div>');
        $('#'+ id).css({'opacity': 0.6,'top': '0px' , 'left': '0px', 'background': '#000', 'z-index': '50', 'cursor': 'pointer'});
        var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
        if (badBrowser) {
            $('#'+ id).css({'height': $('body').height(),  'position': 'absolute', 'width': $('body').height()});
        } else {
            $('#'+ id).css({'height': '100%', 'position': 'fixed', 'width': '100%'});
        }
        $('#'+ id).hide();
    }
}

function removeOverlay(id) {
    if ( typeof(id) == "undefined" || id == "") {
        id='overlay';
    }
    id = id.replace('#','');
    
    if ( $('#'+ id).size() > 0 ) {  //-- Only add if an object with this ID does not already exist
        $('#'+ id).fadeOut(400, function() {
            $(this).remove();
        });
    }
}

//-- END FUNCTIONS



//-- START VALIDATION
$.validator.addMethod('min_years_of_age', function(value, element, min_age) {
    var day = $("#sel_bdayDay").val();
    var month = $("#sel_bdayMonth").val();
    var year = $("#sel_bdayYear").val();
    
    var mydate = new Date();
    mydate.setFullYear(year, month-1, day);

    var currdate = new Date();
    currdate.setFullYear(currdate.getFullYear() - min_age);
    
    return (currdate - mydate < 0 ? false : true);
}, 'You Must be at least 18 years old.');

$(document).ready(function(){
    activateJoinForm();
});

function validateJoinFormError(xml) {
    //-- Clear the old Errors
    $('[generated="true"]').fadeOut('fast',function(){ 
        $(this).html(''); 
    });

    //-- Display the overall message
    errorHtml = '<div class="errors_overall" generated="true">';
    $(xml).find('error message').each(function(){
      errorHtml = errorHtml + $(this).text();
    });
    errorHtml = errorHtml +'</div>';
    $("form:first").prepend(errorHtml);
    //-- Display the specific message
    $(xml).find('error rejected_fields field').each(function(){
        handelXmlErrorMessage(this);
    });
}

function validateJoinFormSuccess(xml) {
    //-- We made our account, now lets set the profile
    $(xml).find('login').each(function(){
      username = $(this).text();
    });
    $(xml).find('account_id').each(function(){
      account_id = $(this).text();
    });
    //-- Disable the other elements so they can't change them.
    $('#joinForm').find('#sel_bdayMonth, #sel_bdayDay, #sel_bdayYear,'+
                        ' #txt_screenName, #txt_emailAddress, #cbx_over18').each(function(){
      $(this).attr('disabled', 'disabled');
    }); //-- End each

    //-- Add the account_id we got back to the profile form
    $('#joinForm').prepend(
        '<input type="hidden" id="account_id" name="account_id" value="'+ account_id +'" />' +
        '<input type="hidden" id="sel_bdayDay_1" name="sel_bdayDay_1" value="'+ $('#sel_bdayDay').val() +'" />' +
        '<input type="hidden" id="sel_bdayMonth_1" name="sel_bdayMonth_1" value="'+ $('#sel_bdayMonth').val() +'" />' +
        '<input type="hidden" id="sel_bdayYear_1" name="sel_bdayYear_1" value="'+ $('#sel_bdayYear').val() +'" />'
    );

    //-- Change the action of the form (so we can click it again if it doesn't work)
    $("#action").val('cp');

    //-- Submit the form again
    $("#joinForm").submit();
}

function validateJoinForm(xml) {
    if ( $(xml).find('error').size() > 0 ) { //-- There's an error
        validateJoinFormError(xml);
    } else {
        validateJoinFormSuccess(xml);
    }
}

function validateAccountFormError(xml) {
    //-- Display the overall message
    errorHtml = '<div class="errors_overall" generated="true">';
    $(xml).find('error message').each(function(){
      errorHtml = errorHtml + $(this).text();
    });
    errorHtml = errorHtml +'</div>';
    $("form:first").prepend(errorHtml);
    //-- Display the specific message
    $(xml).find('error rejected_fields field').each(function(){
        handelXmlErrorMessage(this);
    });
}

function validateAccountFormSuccess(xml) {
    //-- Profile updated, show the login form
    email = $('#txt_emailAddress').val();
    domain = $('#domain').val();
    $('#form').fadeOut('slow', function() {
        $(this).remove();
        $('body').append( 
            '<div id="login" style="display: none;">'+
            '    <div class="content">'+
            '        <div>'+
            '        <h1>Congratulations!</h1>'+
            '        <h2>Your Username and Password has been sent to: '+ email +'</h2>'+
            '        <h3>Enter your password here to start hooking up.</h3>'+
            '        <form id="loginForm" action="http://www.'+ domain +'/login">'+
            '            <label for="login_txt_screenName">Screenname:</label>'+
            '            <p class="input"> <input type="text" id="login_txt_screenName" name="login" value="'+ username +'" /> </p>'+
            '            <label for="login_password">Password:</label> <p class="input"> <input type="password" id="login_password" name="password"/> </p>'+
            '            <input type="submit" id="loginSubmit" value="Login" />'+
            '        </form>'+
            '        </div>'+
            '    </div>'+
            '    <div class="footer clear"></div>'+
            '</div>'
        );
        addOverlay('#overlay');
        $('#overlay').fadeIn(400, function() {
            var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
            if (badBrowser) {
                $('#login').css({'position': 'absolute', 'top': '50px', 'left': ($('body').width()-$('#login').width())/2})
            } else {
                $('#login').css({'position': 'fixed', 'top': '50px', 'left': ($(window).width()-$('#login').width())/2})
            }

            $('#login').fadeIn('slow', function() {
                scrollWindowToElem($(this), 400);
            });

            //-- Have the browser open a window to the email portal if known
            openEmail(email); 
        });
    });
}

function validateAccountForm (xml) {
    if ( $(xml).find('error').size() > 0 ) { //-- There's an error
         validateAccountFormError(xml);
    } else {
        validateAccountFormSuccess(xml);
    }
}

function activateJoinForm () {
    $("#joinForm").validate({
      submitHandler: function(form) {
        $(form).ajaxSubmit({
          type: "POST",
          url: location.href,
          dataType: "xml",
          success:    function(xml) { 
              
              //-- Clear the old Errors
              $('[generated="true"]').fadeOut('fast',function(){ 
                  $(this).html(''); 
              });
              
              if ( 'ca' == $("#action").val() ) {
                validateJoinForm(xml);                
              } else if ( 'cp' == $("#action").val() ) {
                validateAccountForm(xml);
              } else { 
                  //-- We should never get here
                  alert('There has been an error trying to process your account.\nPlease try again later.')
              }
              return false;
          } 
        });
      },
      rules: {
        sel_bdayMonth: { required: true },
        sel_bdayDay: { required: true },
        sel_bdayYear: {
          required: true,
          min_years_of_age: "18"
        },
        txt_screenName: {
          required: true,
          minlength: 3,
          maxlength: 15
        },
        txt_emailAddress: {
          required: true,
          email: true
        },
        cbx_over18: { required: true },
        sel_gender: { required: true },
        cbx_genderPreference_man: { minlength: 1 },
        sel_locCountry: { required: true },
        sel_locState: { required: true },
        sel_locCity: { required: true }
      },
      messages: {
        sel_bdayMonth: { required: "Month field is required" },
        sel_bdayDay: { required: "Day field is required" },
        sel_bdayYear: { required: "Year field is required" },
        txt_screenName: {
          required:  "You must enter a screen name",
          minlength: "Must be atleast 3 chars",
          maxlength: "15 character max"
        },
        txt_emailAddress: {
          required: "You must enter an email",
          email: "That address not appear to be valid"
        },
        cbx_over18: { required: "You must agree to the terms and conditions" },
        sel_gender: { required: "Please select your gender" },
        cbx_genderPreference_man: { minlength: "Please select at least 1 group" },
        sel_locCountry: { required: "You are required to select a country" },
        sel_locState: { required: true },
        sel_locCity: { required: true }
      }
    });
    
    $('#joinForm .enter').click(function () { 
      $('#joinForm').submit(); 
      return false;
    });
}

function handelXmlErrorMessage(element) {
  placeErrorAfterElemID = '#'+ $(element).attr('name').replace('_dup','');
  if ( '#sel_bdayDay' == placeErrorAfterElemID || '#sel_bdayMonth' == placeErrorAfterElemID ) {
    placeErrorAfterElemID = '#sel_bdayYear';    
  }
  if ( '' != placeErrorAfterElemID && $(placeErrorAfterElemID).size() > 0 ) {
      $(placeErrorAfterElemID).after('<span class="helper red" generated="true">'+ $(element).find('error_message').text() +'</span>');
  } else {
      alert('Error ('+ $(element).find('error_message').attr('error_code') +"):\n"+ $(element).find('error_message').text());
  }
}

function openEmail(domainName){
    if (domainName.indexOf('yahoo') != -1){
        window.open("http://mail.yahoo.com");
    }else if (domainName.indexOf('ameritech.net') != -1){
        window.open("http://webmail.att.net");
    }else if (domainName.indexOf('bellsouth.net') != -1){
        window.open("http://webmail.att.net");
    }else if (domainName.indexOf('flash.net') != -1){
        window.open("http://webmail.att.net");
    }else if (domainName.indexOf('pacbell.net') != -1){
        window.open("http://webmail.att.net");
    }else if (domainName.indexOf('prodigy.net') != -1){
        window.open("http://webmail.att.net");
    }else if (domainName.indexOf('sbcglobal.net') != -1){
        window.open("http://webmail.att.net");
    }else if (domainName.indexOf('snet.net') != -1){
        window.open("http://webmail.att.net");
    }else if (domainName.indexOf('swbell.net') != -1){
        window.open("http://webmail.att.net");
    }else if (domainName.indexOf('wans.net') != -1){
        window.open("http://webmail.att.net");
    }else if (domainName.indexOf('hotmail.com') != -1){
        window.open("http://hotmail.com");
    }else if (domainName.indexOf('gmail.com') != -1){
        window.open("http://gmail.com");
    }else if (domainName.indexOf('comcast.net') != -1){
        window.open("http://www.comcast.net");
    }else if (domainName.indexOf('aol.com') != -1){
        window.open("http://mail.aol.com");
    }else if (domainName.indexOf('aol.ca') != -1){
        window.open("http://mail.aol.ca");
    }
}
//-- END VALIDATION
