function allInputsAreFilled(form) {
    var inputs = form.elements;
    for (var i=0;i<inputs.length;i++) {
	if (inputs[i].value == "" && inputs[i].type != "hidden") {
	    alert('You need to fill all fields!');
	    return false;
	}
    }
    return true;
}

function emailsAreMatching(form) {
    if (form.friend_email.value != form.friend_email_confirm.value) {
	alert("Emails don't match");
	return false;
    }
    return true;
}

function validateForm(form_name) {
    var form = document.getElementById(form_name);
    if (allInputsAreFilled(form) && emailsAreMatching(form)) {
        form.submit();
    } else {
        return false;
    }
}

function checkLoginForm(f) {
    var rxTrim = new RegExp("^\\s+|\\s+$", "g");
    if (f.user2.value.toString().replace(rxTrim, "").length < 1) {
        printAlert("Please enter your e-mail address.", f.name + "message");
        f.user2.focus();
        return false;
    }
    if (f.pass2.value.toString().replace(rxTrim, "").length < 1 && f.have_password[1].checked) {
        printAlert("Please enter your password.", f.name + "message");
        f.pass2.focus();
        return false;
    }
    return true;
}

function subjectDropdownChanged() {
    var subject = document.getElementById('subject');
    var reason = document.getElementById('reason_div');
    var subject_div = document.getElementById('subject_div');
    if (subject.selectedIndex=="2") {
        reason.style.display='';
        subject_div.style.display='block';
    } else {
        reason.style.display='none';
        subject_div.style.display='';
    }
}

function updateSizecharts(category_id,section_id){
    var brand_id = $F('brands');
    var sizechart = $('sizechart_content');
    if(brand_id){
	new Ajax.Updater('sizechart_content', '/ajax_requests/update_sizecharts.php?brand_id='+brand_id+'&cat_id='+category_id+'&section_id='+section_id);
	sizechart.show();
    } else {
	sizechart.hide();
    }
}

function initializeFlowPlayerForBehindTheBrandPopup(){
    playFlowPlayer($('btb-video-title').innerHTML,'Behind The Brand Video');
    $("btb-replay").onclick = replayFlowPlayer;

    myLightWindow.addOnDeactivateWindowAction(function(){
	flowplayer("player").stop();
    });
}

function playFlowPlayer(title,type){
    flowplayer("player", "/fp_content/swf/flowplayer/flowplayer.commercial-3.1.1.swf", {
	key: $("player").getAttribute('key'),
	clip: {
	    onFinish: function() {
		Omniture.finishWatchingVideo(title,type);
		showReplayVideoScreen();
	    }
        }
    });
    Omniture.startWatchingVideo(title,type);
}

function showReplayVideoScreen() {
    $('carousel').hide();
    $('btb-end-splash').show();
}

function replayFlowPlayer(){
    $('carousel').show();
    $('btb-end-splash').hide();

    playFlowPlayer($('btb-video-title').innerHTML, 'Behind The Brand Video');
}

function seeAllArticles(){
    $('see_all_articles').style.display = 'block';
    $('see_limited_link_articles').style.display = 'block';
    $('see_all_link_articles').style.display = 'none';
}

function seeLimitedArticles(){
    $('see_all_articles').style.display = 'none';
    $('see_limited_link_articles').style.display = 'none';
    $('see_all_link_articles').style.display = 'block';
}

var NudGiveAwayClass = new Class.create({
    initialize: function() {
	this.sizeSelectName = 'size';
	this.fields = $H({first_name: 'varchar',last_name: 'varchar', address_1: 'varchar', city: 'varchar', zip: 'numeric', email: 'email', confirm_email: 'email', states: 'select', agree_2: 'checkbox', item_id: 'radio', size: 'select'});
	this.fields_errors = $H({first_name: 'First Name Missing',last_name: 'Last Name Missing', address_1: 'Address Missing', city: 'City Missing', zip: 'Invalid Zip Code', email: 'Email Missing', confirm_email: 'Confirm Email Missing', states: 'State Missing', agree_2: 'You must read and agree to the contest rules to submit your entry.', item_id: 'Please choose underwear/panty style', size: 'Size Missing'});
	this.errors = 0;
	this.required = ['first_name','last_name','address_1','city','zip','email','confirm_email', 'states', 'agree_2', 'item_id', 'size'];
	this.submitForm = "submit_form";
	this.clear_form = true;
    },
    
    getSizeByItemId: function(itemId,action) {
	var target = this.sizeSelectName;
	var url = "/ajax_requests/nud_giveaway_ajax_requests.php";
	var params  = {item_id: itemId, action: action};
	var myAjax = new Ajax.Updater(target, url, {method: 'get', parameters: params});
    },
    
    clearSelectEffects: function(input) {
	if(input.value != "" || input.value != "XX1" || input.value != "XX3") {
	    this.removeErrorClass(input);
	    this.setErrorLabel(input.id,'');
	}
    },

    clearFormField: function(input) {
	if(input.value == "Field Required" || input.value == this.fields_errors.get(input.id) || input.value == "Invalid Email Address" || input.value == "E-mail Does Not Match"){
            input.value = "";
	    $(input.id).removeClassName('req');
	    this.removeErrorClass(input);
	}
    },
    
    clearRadioEffects: function() {
	this.setErrorLabel('item_id',"");
    },
    
    clearChecboxEffects: function() {
	if($('agree_2').checked) {
	    this.setErrorLabel('agree_2','');
	}
    },

    isNumeric: function(value) {
	if (value == null || value == '' || !value.toString().match(/^[-]?\d*\.?,?\d*$/)) return false;
	return true;
    },
    
    checkIfElementHasNotDefaultValue: function(element) {
	if(this.fields.get(element) == "numeric") {
	    return $F(element) == "" || $F(element) == "Field Required" || $F(element) == this.fields_errors.get(element) || $F(element) == "Invalid Zip Code" ? true : false;
	}
	if(this.fields.get(element) == "email") {
	    return $F(element) == "" || $F(element) == "Field Required" || $F(element) == this.fields_errors.get(element) || $F(element) == "Invalid Email Address" ? true : false;
	}
	return $F(element) == "" || $F(element) == "Field Required" || $F(element) == this.fields_errors.get(element) ? true : false;
    },
    
    chechIfZipCodeIsValid: function() {
	var zipValueCount =  $F('zip').length;
	if(zipValueCount != 11 && zipValueCount != 5){
	    $('zip').value = "Invalid Zip Code";
	    this.setErrorClass('zip');
	    this.errors++;
	}
    },

    validEmailInput: function(element) {
	var pattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if(null == $F(element).match(pattern)){
	    $(element).value = "Invalid Email Address";
	    this.setErrorClass(element);
	    this.errors++;
	}
	if($F(element)!=$F('email')) {
	    $(element).value = "E-mail Does Not Match";
	    this.setErrorClass(element);
	    this.errors++;
	}
    },
    
    validInput: function(element) {

	if(this.fields.get(element) == "numeric") {
	    if(!this.isNumeric($F(element))){
		$(element).value = this.fields_errors.get(element);
		this.setErrorClass(element);
		this.errors++;
	    }else{
		this.chechIfZipCodeIsValid();
	    }
	}
	
	if(this.fields.get(element) == "email") {
	    if(this.checkIfElementHasNotDefaultValue(element)) {
		$(element).value = this.fields_errors.get(element);
		this.setErrorClass(element);
		this.errors++;
	    }else{
		this.validEmailInput(element);
	    }
	}

	if(this.fields.get(element) == "varchar") {
	    if(this.checkIfElementHasNotDefaultValue(element)) {
		$(element).value = this.fields_errors.get(element);
		this.setErrorClass(element);
		this.errors++;
	    }
        }
	
	if(this.fields.get(element) == 'select'){
	    if($(element).value == "" || $(element).value == "XX1" || $(element).value == "XX3") {
		this.setErrorLabel(element,this.fields_errors.get(element));
		this.setErrorClass(element);
		this.errors++;
	    }
	}
	
	if(this.fields.get(element) == 'checkbox') {
	    if(!$(element).checked ) {
		this.setErrorLabel(element,this.fields_errors.get(element));
		this.errors++;
	    }
	}

	if(this.fields.get(element) == 'radio') {
	    var checked = this.wasPantsRadioChecked();

	    if(!checked) {
		this.setErrorLabel(element,this.fields_errors.get(element));
		this.errors++;
	    }
	    
	}
    },
    
    validForm: function(url,form) {
	var object = Object.clone(this);
        object.errors = 0;

        this.required.each(function(el){
	    object.validInput(el);
	});
	if(object.errors > 0) {
//	    $('states').focus();
	    return false;
	}else{
	    this.sendEmailToFriend();
	    this.clearForm(url);
	    return false;
	}
    },

    sendEmailToFriend: function() {
	var ajax_url = '/ajax_requests/nud_giveaway_ajax_requests.php?action=' + this.submitForm + '&' + Form.serializeElements($('giveawayFm').getElements());
	var target = "recaptcha";
	new Ajax.Updater(target, ajax_url, {
            asynchronous: false,
            evalScripts: true,
            method: 'post',
            onComplete: function(transport) {
		creteReacapthaImage('');
		if(transport.responseText == "0"){
		    $("recaptcha-error").innerHTML = "Please enter the two words exactly as they are displayed below";
		}else{
		    $("recaptcha-error").innerHTML = "";
		    Omniture.submittedNudGiveawayEntry($F('email'));
		    $('giveawayFm').reset();
		}
	    }
        });
    },
    
    clearForm: function(url) {
	if($("recaptcha-error").innerHTML == "") {
	    var ajax_url = '/ajax_requests/nud_giveaway_ajax_requests.php';
	    var target = 'entry_form';
	    var params = {action: "reload entry page"};
	    var myAjax = new Ajax.Updater(target, ajax_url, {method: 'get', parameters: params});
	    AjaxPopup.showSimplePopup(url,{resize:false, resize_y:false,width:500,height:400});
	    myLightWindow.addOnCompleteAction(new Function('', "myLightWindow._toggleTroubleElements('hidden', false);"));
	}
    },
    
    setErrorClass: function(input){
	$(input).removeClassName('normal');
	$(input).addClassName('error');
    }, 

    removeErrorClass: function(input) {
	$(input).removeClassName('error');
	$(input).addClassName('normal');
    }, 

    setErrorLabel: function(input,text){
	$(input + '-error').innerHTML = text;
        $(input + '-error').setStyle("font-weight: bold;");
    },
    
    wasPantsRadioChecked: function() {
	var radios = document.getElementsByName("item_id");
	var checked = false;
	
	for(var i=0; i < radios.length; ++i) {
	    if(radios[i].checked){
		return checked = true;
	    }
	}
	
	return checked;
    },
    
    checkIfSelectSizeWasFilled: function() {
	if(!this.wasPantsRadioChecked() && $('size').options.length == 1){
	    var effectAppear = Effect.Appear('size-info',{
		from: 0.9,
		to: 1,
		duration: 2.0,
		afterFinish: function() { Effect.Fade('size-info', { duration: 2.0 });}
	    });
	}
    }
});

var NudGiveAway = new NudGiveAwayClass();
