Function.implement({ 
    bindWithEvent: function(bind, args){ 
        var self = this; 
        if (args != null) args = Array.from(args); 
        return function(event){ 
            return self.apply(bind, (args == null) ? arguments : [event].concat(args));
        }
    }
});

if( mop == undefined ) var mop = {}
if( mop.util == undefined  ){
    
    mop.util = {};
    
    mop.util.stopEvent = function( e ){
    	if( e && e.stop ){
    		e.stop();
    	}else if( e ){
    		e.returnValue = false;
    	}
    }
    mop.util.JSONSend = function( url, data, options, method ){
    	if( options ){  options.url = url; }else{ options = { url: url }; }
    	if( method == "POST" || !method ){ options.method = "post"; new Request.JSON( options ).post( data ); }else{ options.method = "get"; new Request.JSON( options ).get( data ); }
    }
    mop.util.getValueFromClassName = function( key, aClassName ){
    	if(!aClassName) return false;
    	var classNames = aClassName.split( " " );
    	var result = null;
    	classNames.each( function( className ){
    		if( className.indexOf( key ) == 0 ) result = className.split("-")[1];
    	});
    	return result;
    }    
}

if( ovando == undefined ) var ovando = {}
ovando.sweepstakes = {};

ovando.sweepstakes.onPromoButtonClicked = function( e ){
//		console.log( 'onPromoButtonClicked' );
    mop.util.stopEvent( e );
    document.id("emailSubmitPane").removeClass("hidden");
    document.id("userInfoPane").addClass("hidden");
    document.id("thankYouPane").addClass("hidden");
    document.id( document.body ).scrollTo( 0, 0 );
    ovando.sweepstakes.promoPane.setStyles({
       "opacity" : 0,
       "display" : "block"
    });
    document.id("main").addClass("hidden");
    document.id("footer").addClass("hidden");
    ovando.sweepstakes.resizePane();
    ovando.sweepstakes.promoPane.removeClass("hidden");
    ovando.sweepstakes.promoPane.fade( "in" );
    
    document.id("sweepstakesUserEmail").addEvent( 'keydown', function(e){ if (e.key == "enter") ovando.sweepstakes.submitEmail( null ); });
	
}

ovando.sweepstakes.close = function( e ){
    mop.util.stopEvent( e );
    document.id("main").removeClass( "hidden" );
    document.id("footer").removeClass( "hidden" );    
    ovando.sweepstakes.promoPane.fade( "out" );
    ovando.sweepstakes.clearValues();
}

ovando.sweepstakes.emailSubmitResponse = function( response ){
//    console.log( "emailSubmitResponse", response );
    document.id("emailSubmitPane").unspin();
    ovando.sweepstakes.showForm( response.contactExists );
}

ovando.sweepstakes.showForm = function( contactExists ){
    if( contactExists ){
        document.id( "availableMailingLists" ).addClass( "hidden" );
        document.id( "userAllreadySubscribedContent" ).removeClass("hidden");
    }else{
        document.id( "availableMailingLists" ).removeClass( "hidden" );
        document.id( "userAllreadySubscribedContent" ).addClass("hidden");        
    }
    document.id("emailSubmitPane").addClass( "hidden" );
    document.id("userInfoPane").removeClass( "hidden" );
}

ovando.sweepstakes.onSubmitSubscriberInfoButtonClicked = function( e ){
    mop.util.stopEvent( e );
    $("promoErrors").set( "html", "" );
    $("promoErrors").addClass( "hidden" );
    var selectedMailingLists = [];
    var checkBoxes = document.id( "availableMailingLists" ).getElements( "input[type=checkbox]" );
    checkBoxes.each( function( aCheckbox ){
        if( aCheckbox.getProperty( "checked" ) ) selectedMailingLists.push( aCheckbox.get( "name" ) );
    });
    var sweepstakesName = mop.util.getValueFromClassName( "sweepstakesName", document.id("userInfoPane").get("class") );
    var post = {
        sweepstakesName:sweepstakesName,
        emailAddress:   ovando.sweepstakes.emailAddress,
        firstName:      document.id("sweepstakesFirstName").get("value"),
        lastName:       document.id("sweepstakesLastName").get("value"),
        company:        document.id("sweepstakesCompany").get("value"),
        jobTitle:       document.id("sweepstakesJobTitle").get("value"),
        address1:       document.id("sweepstakesAddress1").get("value"),
        address2:       document.id("sweepstakesAddress2").get("value"),
        phone:          document.id("sweepstakesPhone").get("value"),
        city:           document.id("sweepstakesCity").get("value"),
        state:          document.id("sweepstakesState").get("value"),
        country:        document.id("sweepstakesCountry").get("value"),
        zip:            document.id("sweepstakesZip").get("value"),
        notes:          document.id("sweepstakesNotes").get("value"),
        lists:          selectedMailingLists
    }
//    console.log( ":: POST", post );
    document.id("userInfoPane").spin();
    mop.util.JSONSend( document.id("submitSubscriberInfoButton").get( "href" ) , post, { onComplete: ovando.sweepstakes.addContactResponse.bind( this ) });        
}

ovando.sweepstakes.clearValues = function(){
    document.id("sweepstakesUserEmail").set( "value", "" );
    document.id("sweepstakesFirstName").set( "value", "" );
    document.id("sweepstakesLastName").set( "value", "" );
    document.id("sweepstakesCompany").set( "value", "" );
    document.id("sweepstakesJobTitle").set( "value", "" );
    document.id("sweepstakesAddress1").set( "value", "" );
    document.id("sweepstakesAddress2").set( "value", "" );
    document.id("sweepstakesPhone").set( "value", "" );
    document.id("sweepstakesCity").set( "value", "" );
    document.id("sweepstakesState").set( "value", "" );
    document.id("sweepstakesCountry").set( "value", "" );
    document.id("sweepstakesZip").set( "value", "" );
    document.id("sweepstakesNotes").set( "value", "" );
    $("promoErrors").set( "html", "" );
    $("promoErrors").addClass( "hidden" );
}

ovando.sweepstakes.addContactResponse = function( response ){
    //    console.log( ":: addContactResponse", response );
    if( response.error ){
        var errorMessage = "<h4>Please correct the following errors:</h4>";
        response.errors.each( function( anError, anIndex ){
            document.id( "userInfo" ).getElement( "input[name=" + anError[0] +"]" ).addClass("error");
            errorMessage += "<p>" + anError[1] + "</p>";
        });
        document.id("promoErrors").set( "html", errorMessage );
        document.id("promoErrors").removeClass( "hidden" );
        document.id("userInfoPane").unspin();
        document.id( document.body ).scrollTo( 0, 0 );
        alert( "There were a few errors, please correct them and submit again" );
        return false;
    }
    ovando.sweepstakes.clearValues();
    document.id("userInfoPane").unspin();
    document.id("userInfoPane").addClass("hidden");
    document.id("thankYouPane").removeClass("hidden");
    ovando.sweepstakes.close.delay( 3500, this )
}

ovando.sweepstakes.submitEmail = function( e ){
    document.id("sweepstakesUserEmail").removeEvents();
//    console.log( ":: submitEmail", document.id("emailSubmitPane") );
    mop.util.stopEvent( e );
    document.id("emailSubmitPane").spin();
    ovando.sweepstakes.emailAddress = document.id("sweepstakesUserEmail").get("value");
    mop.util.JSONSend( ovando.sweepstakes.submitEmailButton.get( "href" ) + ovando.sweepstakes.emailAddress , null, { onComplete: ovando.sweepstakes.emailSubmitResponse.bind( this ) });        
}

ovando.sweepstakes.resizePane = function( e ){}

ovando.ToolTip = new Class({
        
    element: null,
    message: null,
    morph: null,
    
    options: {
        offset: { x: 0, y: 12 },
        borderRadius: 4
    },
    
    initialize: function( attachTo, options ){
        this.options = $merge( this.options, options );
		this.title = attachTo.get( "title" );
		this.parentElement = attachTo;
        this.build();
    },
    
    build: function(){
        this.element = new Element( "div", { "class" : "toolTip", styles:{} } );
        var top = new Element( "div", { "class" : "tip-top" } );
        var borderStyle;
        if( ( Browser.safari || Browser.chrome ) && Browser.version < 5 ){ borderStyle = "-webkit-border-radius"; }else if( Browser.firefox && Browser.version < 4 ){ borderStyle = "-moz-border-radius"; }else{ borderStyle = "border-radius"; }
        var message = new Element( "div", { "class" : "message" } );
        if( (Browser.ie && Browser.version >= 9) || !Browser.ie  ) message.setStyle( borderStyle, this.options.borderRadius + "px" );        
        var bot = new Element( "div", { "class" : "tip-bot" } );    
        this.element.adopt( top );
        this.element.adopt( message );
        this.element.adopt( bot );
        document.id( document.body ).adopt( this.element );
        this.setMessage( this.title );
        this.morph = new Fx.Morph( this.element, { duration: 750, transition: Fx.Transitions.Quad.easeOut } );
        this.mouseenter = this.parentElement.addEvent( "mouseenter", this.show.bindWithEvent( this ) );
        this.mouseleave = this.parentElement.addEvent( "mouseleave", this.hide.bindWithEvent( this ) );
        this.mousemove = document.id( document.body ).addEvent( "mousemove", this.onMouseMove.bindWithEvent( this ) );
    },

	onMouseMove: function( e ){
		mop.util.stopEvent( e );
		this.mousepos = { x: e.page.x, y: e.page.y };
	},
    
    followMouse: function(){
		var pos = this.element.getPosition();
		pos.y -= this.element.getOffsetParent().getPosition().y;
		var targety = this.mousepos.y - ( pos.height *.5);
		var dx = ( this.mousepos.x + this.options.offset.x - ( this.element.getSize().x * .5 ) ) - pos.x + this.options.offset.x;
		var dy = targety - pos.y + this.options.offset.y;
		var x = pos.x + dx * .125;
		var y = pos.y + dy * .125;
		var newpos = { "left": x  + this.options.offset.x, "top": y  + this.options.offset.y };
        this.element.setStyles( newpos );
    },
    
    setMessage: function( aMessage ){
        this.element.getElement( ".message" ).set( "html", aMessage );
    },
    
    show: function( e ){
        mop.util.stopEvent( e );
		var pos = this.element.getPosition();
		this.element.setStyles( { "left": e.page.x - this.element.getSize().x*.5, "top": e.page.y + 1.5*this.options.offset.y } );
		clearInterval( this.mousefollow );
		this.mousefollow = this.followMouse.periodical( 25, this );
        this.element.setStyles( { "display": "block", "opacity": 0 } );
		this.morph.cancel();
		this.morph.start.delay( 250,  this.morph, { "opacity" : 1 } );
    },
    
    hide: function( e, destroy ){
        mop.util.stopEvent( e );
		this.parentElement.removeEvent( this.mousefollow );
		clearInterval( this.mousefollow );
		this.morph.cancel();
		this.morph.start( { "opacity" : 0 } );
		if( destroy ) this.destroy.delay( 750, this );
    },

    onFadeOut: function(){
        this.removeEvent( this.mousemove );
		this.element.setStyles( { "top" : "-1000px", "left" : "-1000px" } );
    },
    
	destroy: function(){
		if( this.morph ) this.morph.cancel();
		this.parentElement.removeEvent( this.mouseenter );
		this.parentElement.removeEvent( this.mouseleave );
		document.id(document.body).removeEvent( this.mousemove );
		clearInterval( this.mousefollow );
		this.element.destroy();
		this.morph = this.parentElement = this.element = this.mouseenter = this.mouseleave = null;
	}

});

window.addEvent( "domready", function(){
    ovando.sweepstakes.promoButton = document.id("promoButton");
    ovando.sweepstakes.promoPane = document.id("promoPane");
    if( ovando.sweepstakes.promoButton && ovando.sweepstakes.promoPane ){
        ovando.sweepstakes.submitEmailButton = document.id("submitEmailButton");
        var submitSubscriberInfoButton = document.id( "submitSubscriberInfoButton" );
        submitSubscriberInfoButton.addEvent( "click", ovando.sweepstakes.onSubmitSubscriberInfoButtonClicked.bindWithEvent( this ) );  
        document.id("sweepstakesCloseButton").addEvent( "click", ovando.sweepstakes.close.bindWithEvent( this ) );
        ovando.sweepstakes.submitEmailButton.addEvent( "click", ovando.sweepstakes.submitEmail.bindWithEvent( this ) );
        ovando.sweepstakes.promoButton.addEvent( "click", ovando.sweepstakes.onPromoButtonClicked.bindWithEvent( this ) );
//				console.log( document.id("promoButton") )
    }
});
