/*
 * Front-End scripts
 * 
 * @name default.js
 * @package cnc
 * @version 1.0
 * @since 2010-07-12
 * @author Cristian Ciobanu <cristian@pallasweb.com>
 */

// Raise a popup
function openWindow(url,width,height) {day = new Date();id = day.getTime();window.open(url, id, "toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width="+width+",height="+height+",left="+((screen.width - width)/2)+",top="+((screen.height - height)/2));return false;}
// Open links in a new window
function externalLinks() {if (!document.getElementsByTagName) return;var anchors = document.getElementsByTagName("a");for (var i=0; i<anchors.length; i++) {var anchor = anchors[i];if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")anchor.target = "_blank";}}
// Turns a tag into a link
function href(url) {window.location = url;return false;}
// Some global helpers
var loader = '<img alt="Please wait" src="/assets/ui/loader.gif" class="loader" />',
myInterval;

$(document).ready(function() {
    browserDetection();
    fixIE6alphaTransparency();
    externalLinks();

    if ($('.slide').length > 0) {
        $('.slide').flashembed({src: "assets/flash/slide.swf", wmode:'transparent'});
    }

    $('#nav1 li').hover(function() {
        $(this).find('ul').show();
    }, function() {
        $(this).find('ul').hide();
    });
    
    // Home Slideshow
    if ($('#slideshow').length > 0) {
        myInterval = setInterval("fadeInOut('slideshow')", 5000);
    }
    
    if ($('ul.faq').length>0) {
        $('ul.faq div').hide();
        $('ul.faq a.title').click(function() {
            if($(this).siblings('div').eq(0).css('display') == 'none'){
                //$(this).find('span').html('-');
            } else {
                //$(this).find('span').html('+');
            }
            $(this).siblings('div').toggle();
        });
    }
    
    $('a.player').overlay({
        target: '.overlay',
        top: 20,
        mask: {
            color: '#000',
            loadSpeed: 200,
            opacity: 0.5
        },
        onBeforeLoad: function() {
            clearInterval(myInterval);
            var wrap = this.getOverlay().find(".wrap");
            var media = this.getTrigger().attr("href");
            wrap.html('<div class="video-player"></div>');
            flowplayer('.video-player', {
                src: "assets/player/flowplayer-3.1.5.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();
            myInterval = setInterval("fadeInOut('slideshow')", 5000);
        }
    });

    $.each($('img.gallery'), function(i, e) {
        $(this).overlay({
            target: '.photo-overlay',
            top: 10,
            mask: {
                color: '#000',
                loadSpeed: 200,
                opacity: 0.5
            },
            onLoad: function() {
				$(".photos-scrollable").data("scrollable").seekTo(i, 0);
			}
        });
    });
    $(".photos-scrollable").scrollable();
    
    validateForm = function (e) {
        if (formErrors($(e)) == false) {
            return false;
        }
        if (formSubmit($(e)) == false) {
            return false;
        }
        return true;
    }

});

function inputFocus(e, v) {
    if ($(e).val() == v) {
        $(e).val('');
    }
    $(e).addClass('focus');
}

function inputBlur(e, v) {
    if ($.trim($(e).val()) == '') {
        $(e).val(v);
        $(e).removeClass('focus');
    }
}

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 silentSubmit(wrap) {
    wrap.find('form').submit(function() {
        $.post($(this).attr('action'), $(this).serialize(), function (data) {
            wrap.empty();
            wrap.append($(data).find('#content'));
            silentSubmit(wrap);
        })
        return false;
    });
}

function raisePopup(message) {
    $('div.popup').overlay({
        top: '40%',
        mask: {
            color: '#000',
            loadSpeed: 200,
            opacity: 0.2
        },
        closeOnClick: false,
        load: true,
        onBeforeLoad: function() {
            var wrap = this.getOverlay().find(".wrap");
            wrap.html(message);
        },
        onBeforeClose: function() {
            this.getOverlay().find(".wrap").empty();
        }
    }).load();
}


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() {
        return validateEmail($(this).val()) == null;
    }),
    errors_phone = phones.filter(function() {
        return validatePhone($(this).val()) == null;
    }),
    errors_zip = zips.filter(function() {
        return validateZip($(this).val()) == null;
    });
    $(e).find("span.error").remove();
    if (errors.length) {
        $.each(errors, function(i, v) {
            $(v).after('<span class="error">Please enter ' + $(v).attr('title') + '</span>');
        });
        return false;
    } else if (errors_email.length) {
        $.each(errors_email, function(i, v) {
            $(v).after('<span class="error">Please enter valid email address</span>');
        });
        return false;
    } else if (errors_phone.length) {
        $.each(errors_phone, function(i, v) {
            $(v).after('<span class="error">Please enter valid phone number</span>');
        });
        return false;
    } else if (errors_zip.length) {
        $.each(errors_zip, function(i, v) {
            $(v).after('<span class="error">Please enter valid zip code</span>');
        });
        return false;
    }
    return true;
}

function formSubmit(e) {
    e.find('button[type="submit"]').after(loader);
    $.post(e.attr('action'), e.serialize() + '&jsonly=1', function(data) {
        e.find('.loader').remove();
        if ((data.redirect != undefined) && (data.redirect.length > 0)) {
            window.location.assign(data.redirect);
        }
        if ((data.failure != undefined) && (data.failure.length > 0)) {
            raisePopup(data.failure);
        }
        if ((data.success != undefined) && (data.success.length > 0)) {
            raisePopup(data.success);
            e.find('input:text, select, textarea').val('');
            e.find('input:radio, input:checkbox').removeAttr('checked');
        }
        if ((data.errors != undefined) && ($.makeArray(data.errors).length > 0)) {
            $.each(data.errors, function (i, v) {
                $('#' + i).after('<span class="error">' + v + '</span>');
            });
        }
    }, 'json');
    return false;
}

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

function resetFields(element) {
    $(element).parents('form').find('input').each(function (){
        $(this).val('').removeAttr('value');
    })
    $(element).parents('form').find('select').each(function (){
        $(this).children('option').removeAttr('selected');
    })
}
