
/* FSMachine */

function FSMachine(machineDefinition) {
	for(var _label in machineDefinition) {
		if(_label == 'machine' || _label == 'states' || _label == 'events' || _label == 'parameters') {
			this[_label] = machineDefinition[_label];
		}
	}
	this.transitions = {};
}

$.fn.bindFSMachine = function(definition) {
	var _fsmdef = definition;
	return this.each(function() {
		if (typeof(this.$FSM) == 'undefined') {
			this.$FSM = {};
			var _translabels = [];
			for (var i in _fsmdef.events) {
				_translabels.push("fsm:" + _fsmdef.machine + ":" + _fsmdef.events[i]);
			}
			$(this).bind(_translabels.join(" "), function(event) {
				var _type = event.type.split(":");
				if (_type.length == 3) {
					if (typeof(this.$FSM[_type[1]]) != 'undefined') {
						if (!this.$FSM[_type[1]].locked) {
							this.$FSM[_type[1]].locked = true;
							if (typeof(this.$FSM[_type[1]].transitions[_type[2] + "||" + this.$FSM[_type[1]].currentState]) != 'undefined') {
								this.$FSM[_type[1]].transitions[_type[2] + "||" + this.$FSM[_type[1]].currentState].transition(this, _type[1], event.fsmparams);
								//this.$FSM[_type[1]].currentState = this.$FSM[_type[1]].transitions[_type[2] + "||" + this.$FSM[_type[1]].currentState].nextState;
							}
							this.$FSM[_type[1]].locked = false;
						}
					}
				}
			});
		}
		this.$FSM[_fsmdef.machine] = {
			"events": _fsmdef.events,
			"states": _fsmdef.states,
			"transitions": _fsmdef.transitions,
			"locked": false,
			"currentState": 'uninited'
		};
		for (var i in _fsmdef.parameters) {
			this.$FSM[_fsmdef.machine][_fsmdef.parameters[i]] = null;
		}
		$(this).trigger('fsm:' + _fsmdef.machine + ':init');
	});
}

var FSMToolbox = {};

/* generic machine patterns */

FSMToolbox.toggle = new FSMachine({
	machine:'toggle',
	states:['open','closed'],
	events:['init','toggle'],
	parameters:['openHeight']
});

FSMToolbox.carousel = new FSMachine({
	machine:'carousel',
	states:['default','autoplay','animated'],
	events:['init','goto','autoincrement','end'],
	parameters:['index','size','timer','width']
});

FSMToolbox.email = new FSMachine({
    machine:'email',
    states:['closed','open','submitted','done','invalid'],
    events:['init','open','close','submit','finish','reset']
});

/* 
	transition(dom_element,machine_name,event_parameters);
	'EVENT||STATE':{nextState:'STATE',transition:function(el,machine,parameters) {}},
*/

/* footer link tray */
var FSMFooterTray = FSMToolbox.toggle;

FSMFooterTray.transitions = {
	'init||uninited':{transition:function(el,machine,parameters) {
		el.$FSM[machine].openHeight = $('.link-container').outerHeight();
		$('.link-container',el).css({height:0});
		$('.link-container .float-left:eq(0)',el).each(function() {
			$('.header-container .float-left:eq(0)',el).css({width:$(this).outerWidth(true)});
		});
		$('.link-container .float-left:eq(1)',el).each(function() {
			$('.header-container .float-left:eq(1)',el).css({width:$(this).outerWidth(true)});
		});
		$('.link-container .float-left:eq(2)',el).each(function() {
			$('.header-container .float-left:eq(1)',el).css({width:$('.header-container .float-left:eq(1)',el).width()+$(this).outerWidth(true)});
		});
		$(el).removeClass('outside-the-box');

		el.$FSM[machine].currentState = 'closed';
	}},
	'toggle||open':{transition:function(el,machine,parameters) {
		$('.shape-triangle-down',el).removeClass('shape-triangle-down').addClass('shape-triangle-right');
		$('.link-container',el).stop().animate({height:0},500,'linear');

		el.$FSM[machine].currentState = 'closed';
	}},
	'toggle||closed':{transition:function(el,machine,parameters) {
		$('.shape-triangle-right',el).removeClass('shape-triangle-right').addClass('shape-triangle-down');
		$('.link-container',el).stop().animate({height:el.$FSM[machine].openHeight},500,'linear');
		$('html,body').stop().animate({scrollTop:$(el).offset().top},500,'linear');

		el.$FSM[machine].currentState = 'open';
	}}
};

/* hero carousel */
var FSMHeroCarousel = FSMToolbox.carousel;

FSMHeroCarousel.transitions = {
    'init||uninited': { transition: function (el, machine, parameters) {
        el.$FSM[machine].index = 0;
        el.$FSM[machine].size = $('article', el).length;
        el.$FSM[machine].width = $(el).width();

        if ($(el).is('[ui-carousel-animation=cross-fade]')) {
            if ($('html').is('.ie')) {
                $('article', el).css({ left: 0, zIndex: 1, visibility: 'hidden' }).filter(':first').css({ zIndex: 2, visibility: 'visible' });
            } else {
                $('article', el).css({ left: 0, zIndex: 1, opacity: 0 }).filter(':first').css({ zIndex: 2, opacity: 1 });
            }
        } else {
            $('article:first', el).css({ left: 0 });
        }

        if (el.$FSM[machine].size > 1) {
            el.$FSM[machine].timer = window.setInterval(function () {
                $('.ui-hero-carousel').trigger('fsm:carousel:autoincrement');
            }, 6000);

            $('.ui-hero-carousel-dot-image:first', el).addClass('active');
            el.$FSM[machine].currentState = 'autoplay';
        }
    }
    },
    'autoincrement||autoplay': { transition: function (el, machine, parameters) {

        if ($(el).is('[ui-carousel-animation=cross-fade]')) {
            el.$FSM[machine].index = (el.$FSM[machine].index + 1 >= el.$FSM[machine].size) ? 0 : el.$FSM[machine].index + 1;
            if ($('html').is('.ie')) {
                $('article', el).css({ zIndex: 1, visibility: 'hidden' }).filter(':eq(' + el.$FSM[machine].index + ')').css({ zIndex: 2, visibility: 'visible' });
                el.$FSM[machine].currentState = (el.$FSM[machine].timer != null) ? 'autoplay' : 'default';
                $('.ui-hero-carousel-dot-image', el).removeClass('active').filter(':eq(' + el.$FSM[machine].index + ')').addClass('active');
                 return true;
            } else {
                $('article:eq(' + el.$FSM[machine].index + ')', el).css({ zIndex: 3, opacity: 0 }).animate({ opacity: 1 }, 1200, "swing", function () {
                    $(this).parents('.ui-hero-carousel').find('article').not(this).css({ zIndex: 1, opacity: 0 });
                    $(this).css('zIndex', 2);
                    $('.ui-hero-carousel').trigger('fsm:carousel:end');
                });
            }
        } else {
            var _params = { left: -el.$FSM[machine].width, top: 0 };
            if (!$('html').is('.ie7,.ie8')) {
                _params.opacity = 0;
            }
            $('article:eq(' + el.$FSM[machine].index + ')', el).animate(_params, 1200, "swing");
            el.$FSM[machine].index = (el.$FSM[machine].index + 1 >= el.$FSM[machine].size) ? 0 : el.$FSM[machine].index + 1;
            _params.left = 0;
            if (!$('html').is('.ie7,.ie8')) {
                _params.opacity = 1;
            }
            $('article:eq(' + el.$FSM[machine].index + ')', el).css({ left: el.$FSM[machine].width }).animate(_params, 1200, "swing", function () {
                $('.ui-hero-carousel').trigger('fsm:carousel:end');
            });
        }
        $('.ui-hero-carousel-dot-image', el).removeClass('active').filter(':eq(' + el.$FSM[machine].index + ')').addClass('active');
        el.$FSM[machine].currentState = 'animated';
    }
    },
    'goto||autoplay': { nextState: 'animated', transition: function (el, machine, parameters) {
        if (typeof (parameters.index) != 'undefined' && $('article:eq(' + parameters.index + ')', el).length == 1) {
            window.clearInterval(el.$FSM[machine].timer);
            el.$FSM[machine].timer = null;

            if (parameters.index != el.$FSM[machine].index) {
                if ($(el).is('[ui-carousel-animation=cross-fade]')) {
                    el.$FSM[machine].index = parameters.index;
                    if ($('html').is('.ie')) {
                        $('article', el).css({ zIndex: 1, visibility: 'hidden' }).filter(':eq(' + el.$FSM[machine].index + ')').css({ zIndex: 2, visibility: 'visible' });
                        el.$FSM[machine].currentState = (el.$FSM[machine].timer != null) ? 'autoplay' : 'default';
                        $('html,body').stop().animate({ scrollTop: 0 }, 500, 'linear');
                        $('.ui-hero-carousel-dot-image', el).removeClass('active').filter(':eq(' + el.$FSM[machine].index + ')').addClass('active');
                        return true;
                    } else {
                        $('article:eq(' + el.$FSM[machine].index + ')', el).css({ zIndex: 3, opacity: 0 }).animate({ opacity: 1 }, 1200, "swing", function () {
                            $(this).parents('.ui-hero-carousel').find('article').not(this).css({ zIndex: 1, opacity: 0 });
                            $(this).css('zIndex', 2);
                            $('.ui-hero-carousel').trigger('fsm:carousel:end');
                        });
                    }
                } else {
                    var _moveleft = (parameters.index > el.$FSM[machine].index) ? true : false;
                    var _params = { left: (_moveleft ? '-' : '') + el.$FSM[machine].width, top: 0 };
                    if (!$('html').is('.ie7,.ie8')) {
                        _params.opacity = 0;
                    }
                    $('article:eq(' + el.$FSM[machine].index + ')', el).animate(_params, 1200, "swing");
                    el.$FSM[machine].index = parameters.index;
                    _params.left = 0;
                    if (!$('html').is('.ie7,.ie8')) {
                        _params.opacity = 1;
                    }
                    $('article:eq(' + el.$FSM[machine].index + ')', el).css({ left: (_moveleft ? '' : '-') + el.$FSM[machine].width + 'px' }).animate(_params, 1200, "swing", function () {
                        $('.ui-hero-carousel').trigger('fsm:carousel:end');
                    });
                }

                $('.ui-hero-carousel-dot-image', el).removeClass('active').filter(':eq(' + el.$FSM[machine].index + ')').addClass('active');
                el.$FSM[machine].currentState = 'animated';
            }
        }
    }
    },
    'end||animated': { transition: function (el, machine, parameters) {
        el.$FSM[machine].currentState = (el.$FSM[machine].timer != null) ? 'autoplay' : 'default';
    }
    }
};

FSMHeroCarousel.transitions['goto||default'] = FSMHeroCarousel.transitions['goto||autoplay'];

/* header menu flyout */

$.fn.modal = function (modals) {
    return this.each(function () {
        this.modals = modals;
        this.init = function () {
            $('body').append('<div id="modal-mask" style="position:absolute;top:0;left:0;width:100%;height:100%;display:none;background:#fff;z-index:995;"></div>');
            $(window).bind("scroll resize", function () {
                $('#modal-mask').css({ top: $(window).scrollTop(), left: $(window).scrollLeft() });
                $('#modal-content').css({ top: Math.max(0, $(window).scrollTop() + (($('body').height() - $('#modal-content').height()) / 2)), left: $(window).scrollLeft() + (($('body').width() - $('#modal-content').width()) / 2) });
            });
            $('#modal-mask')[0].hide = function () {
                $('#modal-mask').animate({ opacity: 0 }, 300, "linear", function () { $(this).css({ display: 'none' }); });
                $('#modal-content').css({ display: 'none' });
                $('[modalopen=true]').attr('modalopen', '').trigger('uimodal:close');
            }
            $('#modal-mask')[0].show = function (id) {
                $(this).css({ display: 'block', opacity: 0 }).animate({ opacity: 0.75 }, 300, "linear");
                $('#modal-content').css({ display: 'block' });
                $('#' + id).attr('modalopen', 'true').trigger('uimodal:open');
                $(window).triggerHandler('resize');
            }
            $('#modal-mask').click(function () {
                this.hide();
            });
        }
        this.init();
    });
}

$(document).ready(function () {

    $('[emailoverlay=emailoverlay]').each(function () {

        this.locked = false;

        $('[emailoverlay=reset]', this).click(function () {
            $(this).parents('[emailoverlay=emailoverlay]')[0].reset();
        });

        $('[emailoverlay=submit]').click(function () {

            var _emailoverlay = $(this).parents('[emailoverlay=emailoverlay]')[0];

            if (!_emailoverlay.locked) {
                _emailoverlay.locked = true;

                var _isvalid = true;
                var _emailregex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

                if ($('#share-email-name').val().match(/\S/)) {
                    $('#share-email-name').parent('span').parent('div').prev('div.error').css({ display: 'none' });
                }
                else {
                    $('#share-email-name').parent('span').parent('div').prev('div.error').css({ display: 'block' });
                    _isvalid = false;
                }

                if (_emailregex.test($('#share-email-sender-address').val())) {
                    $('#share-email-sender-address').parent('span').parent('div').prev('div.error').css({ display: 'none' });
                }
                else {
                    $('#share-email-sender-address').parent('span').parent('div').prev('div.error').css({ display: 'block' });
                    _isvalid = false;
                }

                var _recipients = $('#share-email-recipient-address').val().split(",");

                if (_recipients.length > 0) {
                    for (var i = 0; i < _recipients.length; i++) {
                        if (!_emailregex.test(_recipients[i])) {
                            $('#share-email-recipient-address').parent('span').parent('div').prev('div.error').css({ display: 'block' });
                            _isvalid = false;
                        }
                    }

                    if (_isvalid) {
                        $('#share-email-recipient-address').parent('span').parent('div').prev('div.error').css({ display: 'none' });
                    }
                }
                else {
                    $('#share-email-recipient-address').parent('span').parent('div').prev('div.error').css({ display: 'block' });
                    _isvalid = false;
                }

                if (_isvalid) {
                    $.get("/EmailService.aspx", {
                        sname:$('#share-email-name').val(),
                        semail:$('#share-email-sender-address').val(),
                        remail:$('#share-email-recipient-address').val(),
                        type:($('.recipe-detail').length > 0) ? "recipe" : "article",
                        url:document.location.href,
                        aurl:$('.ui-page-tools .email').attr('emailarticleimage'),
                        rurl:$('#RecipeImage img').attr('src'),
                        rfbr:$.trim($('#RecipeFiber').text())+" of fiber",
                        rname:$.trim($('#RecipeTitle').text()),
                        rprep:"Prep Time: "+$.trim($('#RecipePrepTime').text()),
                        rquant:"Makes: "+$.trim($('#RecipeQuantity').text()),
                        rtime:"Start to Finish: "+$.trim($('#RecipeTotalTime').text()),
                        //rstars:"/ui/img/icon-red-star.png"
                        rstars: "ui/img/blank.gif"
                    }, function (response) {

                        //response = $.parseJSON(response);

                        if (true) {
                            $('.page-email-overlay-success').css({ display: 'block' });
                            $('.page-email-overlay-form').css({ display: 'none' });
                        }
                        else {
                            $('.page-email-overlay-failure').css({ display: 'block' });
                            $('.page-email-overlay-form').css({ display: 'none' });
                        }

                        _emailoverlay.locked = false;
                    });
                }
                else {
                    _emailoverlay.locked = false;
                }
            }
        });

        this.reset = function () {
            $('.page-email-overlay-success,.page-email-overlay-failure').css({ display: 'none' });
            $('.page-email-overlay-form').css({ display: 'block' });
            $('input:text', this).val("");
            $('div.error', this).css({ display: 'none' });
        }

        $('#modal-email-form').bind('uimodal:open', function () {
            this.reset();
        });

        $('.RecipeRatingsControl').parent().bind('click', function () {
            //console.log('entering the RecipeRatinsControl.click() handler');
            var thisRecipe = document.location.href.substring(document.location.href.lastIndexOf('/') + 1);
            //console.log(thisRecipe);
            window.open('/recipes/' + thisRecipe + '/rate?rid=' + $(this).attr('data-rid'), 'Rate', 'width=325,height=240,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,copyhistory=yes,resizable=yes');
        });
    });
});

var siteui = {};

$('html').removeClass('no-js');

