/*
 * Primary Scripts
 * I &heart; HTML5 Boilerplate
 * Author       : Ciobanu N. Cristian <ciobanu.n.cristian@gmail.com>
 * Created on   : Oct 29, 2010, 11:00:00 AM
 */

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

$(document).ready(function() {
    // Default AJAX call settings
    $.ajaxSetup({
        timeout: 3000,
        error:function(x,e){
            if('parsererror'==e) {
                alert('Sorry, we ran into a technical problem (parse error). Please try again...');
            } else if('timeout'==e) {
                alert('Request timed out. Please try again...');
            } else if ( "status" in x ) {
                if(0 == x.status) {
                    alert('You are offline! Please check your network.');
                } else if (404 == x.status) {
                    alert('Sorry, we ran into a technical problem (404). Please try again...');
                } else if (500 == x.status) {
                    alert('Sorry, we ran into a technical problem (500). Please try again...');
                }
            } else {
                alert('Sorry, we ran into a technical problem (unknown error). Please try again...');
            }
        }
    });
    // 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.trigger-popup').length > 0) {
        $('a.trigger-popup').overlay({
            target: '.overlay',
            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="player"></div>');
                $f('.player', {
                    src: "assets/flash/flowplayer-3.2.5.swf",
                    version: [9, 115]
                }, {
                    clip: media,
                    autoPlay: true,
                    autoBuffering: true
                });
            },
            onBeforeClose: function() {
                $f().stop();
                this.getOverlay().find(".wrap").empty();
            }
        });
    }
    if ($('a.player').length > 0) {
        $.each($('a.player'), function(i, e) {
            var media = $(this).attr("href");
            $f('.player', {
                src: "assets/flash/flowplayer-3.2.5.swf",
                version: [9, 115]
            }, {
                clip: media,
                autoPlay: false,
                autoBuffering: true
            });
        });
    }
    // Gallery
    if ($('.gallery .item a').length > 0) {
        $.each($('.gallery .item a'), function(i, e) {
            $(this).overlay({
                top: 100,
                target: '.gallery-overlay',
                mask: {
                    color: '#000',
                    loadSpeed: 200,
                    opacity: 0.5
                },
                onLoad: function() {
                    $(".gallery-scrollable").data("scrollable").seekTo(i, 0);
                }
            });
        });
        $(".gallery-scrollable").scrollable({disabledClass:'invisible', circular:false, keyboard:true, mousewheel: true}).autoscroll({autoplay: false, interval: 3000});
        $(".gallery-scrollable").data("scrollable").onSeek(function() {
            var i = 0;
            var newHeight = 0;
            var scrollIndex = this.getIndex();
            this.getItems().each(function() {
                if(i == scrollIndex) {
                    newHeight = $(this).height();
                    return false;
                }
                i++;
            });
            this.getRoot().add(this.getItemWrap()).animate({
                height : newHeight
            });
        });
    }
    // Scrollable
    if ($('.scrollable').length > 0) {
        $('.scrollable').scrollable({disabledClass:'invisible', circular:false, keyboard:true, mousewheel: true}).autoscroll({autoplay: false, interval: 3000});
    }
    // 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);
        });
    }
    // Validate forms
    $('form').submit(function() {
        return formErrors($(this));
    });
    // Newsticker
    if ($('#announce ul').length > 0) {
        $('#announce ul').newsticker();
    }
});

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;
}

function dtCounter(seconds) {
    if (seconds > 0) {
        minutes = Math.floor(seconds / 60);
        seconds_left = seconds % 60;
        hours = Math.floor(minutes / 60);
        minutes_left = minutes % 60;
        days = Math.floor(hours / 24);
        hours_left = hours % 24;
        if (days > 0) {
            $('#dt-day > span').html(days);
            $('#dt-day').show();
        } else {
            $('#dt-day > span').html(days);
            $('#dt-day').hide();
        }
        if (hours_left > 0) {
            $('#dt-hour > span').html(hours_left);
            $('#dt-hour').show();
        } else {
            $('#dt-hour > span').html(hours_left);
            $('#dt-hour').hide();
        }
        if (minutes_left > 0) {
            $('#dt-minute > span').html(minutes_left);
            $('#dt-minute').show();
        } else {
            $('#dt-minute > span').html(minutes_left);
            $('#dt-minute').hide();
        }
        if (seconds_left > 0) {
            $('#dt-second > span').html(seconds_left);
            $('#dt-second').show();
        } else {
            $('#dt-second > span').html(seconds_left);
            $('#dt-second').hide();
        }
        setTimeout("dtCounter(" + (seconds - 1)  + ")", 1000);
    } else {
        $('#dt-graphic').removeClass('closed').addClass('opened');
        var dt = new Date(),
            dt_day = dt.getDate(),
            dt_month = dt.getMonth(),
            dt_hour = dt.getHours(),
            dt_min = dt.getMinutes(),
            dt_sec = dt.getSeconds(),
            dt_suffix = (dt_hour < 12) ? "AM" : "PM",
            dt_month_name = '',
            i = 0;
        for (i=0;i<months.length;i++) {
            if (i == dt_month) {
                dt_month_name = months[i];
            }
        }
        dt_hour = ( dt_hour > 12 ) ? dt_hour - 12 : dt_hour;
        dt_hour = ( dt_hour == 0 ) ? 12 : dt_hour;

        $('#dt-text').html('<p>We are now <span class="red">open</span><br><span id="dt-month">' + dt_month_name + '</span> <span id="dt-day">' + dt_day + '</span><br><span id="dt-hour">' + dt_hour + '</span>:<span id="dt-minute">' + dt_min + '</span>:<span id="dt-second">' + dt_sec + '</span><span id="dt-suffix">' + dt_suffix + '</span><br><br>Emergency animal hospitals are open at night and on holidays.</p>');
    }
}
