/*
 * Primary Scripts
 * Author       : Ciobanu N. Cristian <ciobanu.n.cristian@gmail.com>
 * Created on   : Aug 23, 2010, 3:00:00 PM
 */

$(document).ready(function() {
    // TinyMCE
    $('textarea.mce').focus(function() {
        $(this).tinymce({
            script_url : '../mce/tiny_mce.js',
            theme: "advanced",
            skin : "o2k7",
            skin_variant : "silver",
            forced_root_block : false,
            force_br_newlines : true,
            force_p_newlines : false,
            plugins : "safari,pagebreak,style,table,save,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,xhtmlxtras",
            theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontsizeselect,|,print,fullscreen,|,cleanup,removeformat,code,help",
            theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,|,insertdate,inserttime,preview,|,forecolor,backcolor",
            theme_advanced_buttons3 : "tablecontrols,|,hr,visualaid,|,sub,sup,cite,abbr,acronym,del,ins,attribs,|,ltr,rtl,|,charmap,emotions,iespell,media",
            theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_align : "left",
            theme_advanced_statusbar_location : "bottom",
            theme_advanced_resizing : true,
            theme_advanced_resizing_use_cookie : false,
            apply_source_formatting : false,
            content_css : "assets/css/tinymce.css",
            remove_script_host : false,
            relative_urls : false

        });
    });
    // Pulsing notifications
    if ($('div.notification').length > 0) {
        $.each($('div.notification'), function(i, e) {
            notification = $(this);
            notification.hide();
            notification.slideDown(function()  {
                notification.css({
                    "opacity":0.8
                });
            });
            notification.click(function() {
                notification.slideUp();
            });
        })
    }
    // Infinite replication
    if ($('ol.row-template').length > 0) {
        $('ol.row-template').hide();
        $('a.row-template-add').click(function() {
            $template = $(this).parent().next('ol.row-template');
            $template.parent().append($template.clone(true).removeClass('row-template').show());
            return false;
        });
        $('a.row-template-rmv').click(function() {
            $(this).parents('ol').eq(0).remove();
            return false;
        });
        $('a.row-template-add').click();
    }
    // Video Player
    if ($('a.player').length > 0) {
        $('a.player').overlay({
            target: '.overlay',
            top: 100,
            mask: {
                color: '#000',
                loadSpeed: 200,
                opacity: 0.5
            },
            onBeforeLoad: function() {
                var wrap = this.getOverlay().find(".wrap");
                var media = this.getTrigger().attr("href");
                wrap.html('<div class="video-player"></div>');
                flowplayer('.video-player', {
                    src: "assets/flash/flowplayer-3.2.4.swf",
                    version: [9, 115],
                    onFail: function()  {
                        wrap.html("You need the latest Flash version to view MP4 movies. Your version is " + this.getVersion());
                    }
                }, {
                    clip: media
                });
            },
            onBeforeClose: function() {
                this.getOverlay().find(".wrap").empty();
            }
        });
    }
    if ($('a.video-player').length > 0) {
        $.each($('a.video-player'), function(i, e) {
            var media = $(this).attr("href");
            flowplayer('.video-player', {
                src: "assets/flash/flowplayer-3.2.4.swf",
                version: [9, 115]
            }, {
                clip: media,
                autoPlay: true,
                autoBuffering: true
            });
        });
    }
    // Scrollable
    if ($('.scrollable').length > 0) {
        $('.scrollable').scrollable({disabledClass:'invisible', circular:true, keyboard:false}).autoscroll({autoplay: true, interval: 10000});
    }
    // Newsticker
    if ($('#newsticker ul').length > 0) {
        $('#newsticker ul').newsticker();
    }
    // Date (Range) input
    if ($('.date').length > 0) {
        $(".date").dateinput({format: 'yyyy-mm-dd', trigger: true});
    }
    if ($('.date-range').length > 0) {
        $(".date-range").dateinput({format: 'yyyy-mm-dd', trigger: true, min: -1});
        $(".date-range").bind("onShow onHide", function()  {
            $(this).parent().toggleClass("active");
        });
        $(".date-range:first").data("dateinput").change(function() {
            $(".date-range:last").data("dateinput").setMin(this.getValue(), true);
        });
    }
});

// See: http://jonraasch.com/blog/a-simple-jquery-slideshow
function fadeInOut(selector) {
    var $active = $('#' + selector + ' img.active');
    if ( $active.length == 0 ) $active = $('#' + selector + ' img:last');
    var $next =  $active.next().length ? $active.next() : $('#' + selector + ' img:first');
    $active.addClass('last-active');
    $next.css({
        opacity: 0.0
    })
    .addClass('active')
    .animate({
        opacity: 1.0
    }, 1000, function() {
        $active.removeClass('active last-active');
    });
}

function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    return email.match(re)
}

function validatePhone(phone) {
    var re = /^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/
    return phone.match(re)
}

function validateZip(zip) {
    var re = /^\d{5}?$/
    return zip.match(re)
}

function formErrors(e) {
    var inputs = $(e).find(".required"),
    emails = $(e).find(".email"),
    phones = $(e).find(".phone"),
    zips = $(e).find(".zip"),
    errors = inputs.filter(function() {
        return $(this).val().replace(/\s*/g, '') == '';
    }),
    errors_email = emails.filter(function() {
        if ($(this).val().replace(/\s*/g, '') != '') {
            return validateEmail($(this).val()) == null;
        } else {
            return false;
        }
    }),
    errors_phone = phones.filter(function() {
        if ($(this).val().replace(/\s*/g, '') != '') {
            return validatePhone($(this).val()) == null;
        } else {
            return false;
        }
    }),
    errors_zip = zips.filter(function() {
        if ($(this).val().replace(/\s*/g, '') != '') {
            return validateZip($(this).val()) == null;
        } else {
            return false;
        }
    });
    $(e).find("span.failure").remove();
    if (errors.length) {
        $.each(errors, function(i, v) {
            if (($(v).attr('title') == undefined) || ($(v).attr('title') == '')) {
                $(v).after('<span class="failure">' + $(v).data('title') + '</span>');
            } else {
                $(v).after('<span class="failure">' + $(v).attr('title') + '</span>');
            }
        });
        return false;
    } else if (errors_email.length) {
        $.each(errors_email, function(i, v) {
            $(v).after('<span class="failure">Please enter valid email address</span>');
        });
        return false;
    } else if (errors_phone.length) {
        $.each(errors_phone, function(i, v) {
            $(v).after('<span class="failure">Please enter valid phone number</span>');
        });
        return false;
    } else if (errors_zip.length) {
        $.each(errors_zip, function(i, v) {
            $(v).after('<span class="failure">Please enter valid zip code</span>');
        });
        return false;
    }
    return true;
}
