/*
 * 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" />',
    popup   = null,
    overlay = null,
    tabs    = null;

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

    initApp();

    if ($('ul.faqs').length > 0) {
        $('ul.faqs div.secure').hide();
        $('ul.faqs p.title a').click(function() {
            $(this).parent().next('div.secure').toggle();
            return false;
        });
    }

    $('div.scrollable').scrollable({circular:true, vertical:true, mousewheel:true, keyboard:false}).autoscroll({autoplay:true});

    tabs = $("ul.tabs").tabs("div.panes > div", {
        effect:'dynamic',
        history:true,
        api:true
    });
    

    $('form.fancy-signup').submit(function() {
        if ($.trim($('#signup-email').val()) == '') {
            raisePopup('<div class="icon icon-symbol-delete">Please enter your email address.</div>');
            return false;
        } else if (validateEmail($('#signup-email').val()) == null) {
            raisePopup('<div class="icon icon-symbol-delete">Please enter valid email address.</div>');
            return false;
        }
        var form = $(this);
        $.post(form.attr('action'), form.serialize() + '&jsonly=1', function(data) {
            if ((data.redirect != undefined) && (data.redirect.length > 0)) {
                location.assign(data.redirect);
            } else if ((data.success != undefined) && (data.success.length > 0)) {
                raisePopup(data.success);
            } else if ((data.failure != undefined) && (data.failure.length > 0)) {
                raisePopup(data.failure);
            } else if ((data.errors != undefined) && ($.makeArray(data.errors).length > 0)) {
                location.assign(form.attr('action') + '?' + form.serialize());
            }
        }, 'json');
        return false;
    });
});

$.tools.tabs.addEffect("dynamic", function(i, done) {
    tab = this.getTabs().eq(i);
    pane = this.getPanes().eq(0);
    if (tab.attr('href') != undefined) {
        if (tab.hasClass('nofollow') == false) {
            url = tab.attr('href');
            pane.html(loader);
            $.post(url, function(data) {
                pane.html($(data).find('#content'));
                pane.show();
                initApp();
                done.call();
            });
        } else {
            window.location.assign(tab.attr('href'));
            done.call();
        }
    }
    done.call();
});

function initApp() {
    $('select.fancy-select').selectmenu({
        style:'dropdown',
        maxHeight: 400
    });

    $('select.fancy-select-complex').selectmenu({
        style:'dropdown',
        menuWidth: 500,
        maxHeight: 400,
        format: function(text){
            var newText = text;
            var findreps = [
                {find:/^([^\~]+) \~ /g, rep: '<span class="ui-selectmenu-item-header">$1</span>'},
				{find:/([^\|><]+) \| /g, rep: '<span class="ui-selectmenu-item-content">$1</span>'},
            ];

            for(var i in findreps){
                newText = newText.replace(findreps[i].find, findreps[i].rep);
            }
            return newText;
        }
    });

    $('.hidden').hide();

    $('[title]').tooltip({
        opacity: 0.9,
        position: "center right"
    });
}

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 submitUrl(e) {
    if ($(e).attr('href') != undefined) {
        $.post($(e).attr('href'), 'jsonly=1', function(data) {
            if ((data.success != undefined) && (data.success.length > 0)) {
                raisePopup(data.success);
            }
            if ((data.failure != undefined) && (data.failure.length > 0)) {
                raisePopup(data.failure);
            }
            if ((data.actions != undefined) && ($.makeArray(data.actions).length > 0)) {
                $.each(data.actions, function (i, v) {
                    if (v == 'rmv') {
                        $('#' + i).remove();
                    }
                    if (v == 'hide') {
                        $('#' + i).hide();
                    }
                    if (v == 'show') {
                        $('#' + i).show();
                    }
                });
            }
            if ((data.reload != undefined) && (data.reload == 1)) {
                if (tabs !== null) {
                    index = tabs.getIndex();
                    tabs.click(tabs.getTabs().length - 1);
                    tabs.click(index);
                }
            }
            if ((data.redirect != undefined) && (data.redirect.length > 0)) {
                window.location.assign(data.redirect);
            }
        }, 'json');
    }
    return false;
}

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

function raiseOverlay(url) {
    if (overlay == null) {
        overlay = $('div#overlay').overlay({
            top: '15%',
            mask: {
                color: '#000',
                loadSpeed: 200,
                opacity: 0.2
            },
            closeOnClick: false,
            api: true,
            onBeforeClose: function() {
                this.getOverlay().find(".wrap").empty();
            }
        });
    }
    overlay.onBeforeLoad(function() {
        var wrap = this.getOverlay().find(".wrap");
        wrap.load(url + ' #content');
    });
    overlay.onLoad(function() {
        var wrap = this.getOverlay().find(".wrap");
        silentSubmit(wrap);
    });
    overlay.load();
    return false;
}

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.error").remove();
    if (errors.length) {
        $.each(errors, function(i, v) {
            if (($(v).attr('title') == undefined) || ($(v).attr('title') == '')) {
                $(v).after('<span class="error">' + $(v).data('title') + '</span>');
            } else {
                $(v).after('<span class="error">' + $(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.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.failure != undefined) && (data.failure.length > 0)) {
            raisePopup(data.failure);
        }
        if ((data.errors != undefined) && ($.makeArray(data.errors).length > 0)) {
            $.each(data.errors, function (i, v) {
                $('#' + i).after('<span class="error">' + v + '</span>');
            });
        }
        if ((data.reload != undefined) && (data.reload == 1)) {
            if (tabs !== null) {
                index = tabs.getIndex();
                tabs.click(tabs.getTabs().length - 1);
                tabs.click(index);
            }
        }
        if ((data.redirect != undefined) && (data.redirect.length > 0)) {
            window.location.assign(data.redirect);
        }
    }, 'json');
    return false;
}

function validateForm(e) {
    if (formErrors($(e)) == false) {
        return false;
    }
    if (formSubmit($(e)) == false) {
        return false;
    }
    return true;
}

function showActions(e) {
    $(e).find('.actions').show();
}

function hideActions(e) {
    $(e).find('.actions').hide();
}

function changeAccountDetails(e) {
    $('#' + e).find('.actions').toggle();
    $('#' + e).find('ul.list').toggle();
    $('#' + e).find('div.form').toggle();
}

function dealTime(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) {
            $('#deal-days > em').html(days);
            $('#deal-days').show();
        } else {
            $('#deal-days > em').html(days);
            $('#deal-days').hide();
        }
        $('#deal-hours > em').html(hours_left);
        $('#deal-minutes > em').html(minutes_left);
        if (days > 0) {
            $('#deal-seconds > em').html(seconds_left);
            $('#deal-seconds').hide();
        } else {
            $('#deal-seconds > em').html(seconds_left);
            $('#deal-seconds').show();
        }
        setTimeout("dealTime(" + (seconds - 1)  + ")", 1000);
    }
}

function updateQty(e, a, f) {
    if (($.trim($(e).val()) != '') || (f == 1)) {
        $.post(a, 'qty=' + $(e).val() + '&jsonly=1&process=1', function(data) {
            if ((data.qty != undefined) && (data.qty > 0)) {
                $(e).val(data.qty);
                $('#deal-item-price').html((data.qty * parseFloat($('#deal-item-unit').html())).toFixed(2));
            } else {
                $(e).val('1');
                $('#deal-item-price').html($('#deal-item-unit').html());
            }
            $('#deal-item-total').html($('#deal-item-price').html());
        }, 'json');
    }
}

function raiseGift(e) {
    gift = $('#gift-form').overlay({
        top: '15%',
        mask: {
            color: '#000',
            loadSpeed: 200,
            opacity: 0.2
        },
        closeOnClick: false,
        api: true
    });
    gift.load();
    return false;
}

function useCredit(e, a) {
    if ($(e).attr('checked') == false) {
        $('#billing-area').show();
    } else {
        $.post(a, '&jsonly=1&process=1', function(data) {
            if ((data.credit != undefined) && (data.credit == 1)) {
                $('#billing-area').hide();
            } else {
                $('#billing-area').show();
            }
        }, 'json');
    }
}
