var rulesLoaded = 0;

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 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 loadRules() {
    var response;
    if (rulesLoaded == 0) { // Don't request again if it's already loaded
        new Ajax.Request('./rules.jsp',
        {
            method:'get',
            parameters: {rem: 1}, 
            onSuccess: function(transport) {
		response = transport.responseText || "no response text";
            },
            onFailure: function() {
		response = "Rules failed to load";
            },
            onComplete: function() {
		Df.Lightbox.setContent(response).show();
		rulesLoaded = 1;
            }
        });
    } else {
        Df.Lightbox.show();
    }
}
function processSignUpFrm() {
    var validForm = true;
 
	// group phone number parts
    if ($('phone1') && $('phone2') && $('phone3')) {
		$('billPhone').value = $('phone1').value + "-" + $('phone2').value + "-" + $('phone3').value;
    }
	
    // check age
    var currDate = new Date();
    var birthDate = new Date();
    birthDate.setFullYear($('dobYear').value,($('dobMonth').value-1),$('dobDay').value);
    
    var diffYear = currDate.getFullYear() - birthDate.getFullYear();
    var diffMonth = currDate.getMonth() - birthDate.getMonth();
    var diffDay = currDate.getDate() - birthDate.getDate();
    // check email format
    if ((diffYear > 13) || ((diffYear == 13) && (diffMonth >= 0) && (diffDay >= 0))) {
		// Is 13 years old or older
    } else {
		alert("You must be over the age of 13 to enter.");
		validForm = false;
    }
    var atPos = $('emailAddress').value.indexOf("@");
    var dotPos = $('emailAddress').value.lastIndexOf(".");
    if ((atPos > 0) && (dotPos-atPos > 1)) {
		// Email is valid
    } else {
		alert("Invalid email format.");
		validForm = false;
    }
	
	// check cookie for recent submission
	secret09Cookie = getCookie('secret09');
	if ((secret09Cookie != null) && (secret09Cookie != "")) {
		validForm = false;
  		alert("You have already submitted an entry within the past 24 hours.  Try again later.");
  	} else if (validForm) {
  		var secret09 = new Date();
  		if (secret09 != null && secret09 != "") {
    		setCookie('secret09',secret09.getTime(),1);
    	}
    }
    // return valid or invalid form status
    return validForm;
}

function clearField(elem) {
    elem.focus();
    if ((elem.value == "mm") || (elem.value == "dd") || (elem.value == "yyyy")) {
	elem.value = "";
        elem.writeAttribute({
	    value : ""
        });
    }
}
Event.observe(window, 'load', function(e) {
	// hide noscript text
	var noscripts = document.getElementsByTagName('noscript');
	for (var i=0; i<noscripts.length; i++) {
	    noscripts[i].style.display = "none";
	}
	if ($('sweepFrm')) { // if on entry form
	    // unlock the submit button
	    $('submit').writeAttribute({
		disabled : null							  
	    });
	    $('sweepFrm').writeAttribute({
		action : "/emailHandler/index.jsp"
	    });
	
	    // prep input elements with preset values as indicators
	    $('dobDay').writeAttribute({
		    value : "dd",
		    onmousedown : "clearField(this)",
		    onfocus : "clearField(this)"
	    });
	    $('dobMonth').writeAttribute({
		    value : "mm",
		    onmousedown : "clearField(this)",
		    onfocus : "clearField(this)"
	    });
	    $('dobYear').writeAttribute({
		    value : "yyyy",
		    onmousedown : "clearField(this)",
		    onfocus : "clearField(this)"
	    });
	}
    
    // lightbox animation parameters
    pars = {
        animate: {
	    time: 150,
	    opacity:.75
	}        
    }
	
    // set up lightbox
    Df.Modal.setPars(pars);
    Df.Shells = {
		dialog : function(holder) {
			if(!holder) {
				holder = document.body
			}
			var dialog = Df.e('div', $(holder) ,{className: 'dialog'});
			var title = Df.e('div', dialog ,{className: 'title'});
			var close = Df.e('span', title ,{innerHTML: 'close'});
			close.observe('click', Df.Lightbox.hide);
			var content = Df.e('div', dialog);
			return {
				element : dialog, 
				content : content
			}
		}
    }
		
    Df.Lightbox.createDialog(
	new Df.Dialog(
	    Df.Shells.dialog()
        ).set({
            animate: {
                time: 150,
                opacity:.99
            },
            drag: false,
            resize: false
        })
    );
		
    Df.Lightbox.getDialog().element.observe(':size', function(e){
        this.getElement().center()
    }.bind(Df.Lightbox.getDialog()));		
                
    // Convert link to rules into call to lightbox with asynch call for rules page content
    var popUpLnk = $('sweeps').select('[class="officialRulesLnk"]');
    for (var i=0; i<popUpLnk.length; i++) {
		popUpLnk[i].writeAttribute({
			href : "javascript:loadRules(this)",
			onclick : "this.blur()"
		});
    }
});
