/*
 * home / home.js
 * Modify: Fri, 1 July 2011 03:08:41 GMT
 * Required jQuery Library 1.6
 */

/*
 * js path defined
 */
var path = (function (root) {

    'use strict';

    var js = root + 'Public/Js/';
    var jquery = js + 'jQuery/';
    var paths = {
        ajax: root + 'HomeAjax/',
        css: root + 'Public/Css/',
        script: js,
        upload: root + 'Public/pic/',
        ckeditor: js + 'ckeditor/',
        tinymce: js + 'tiny_mce/',
        plugin: {
            s               : jquery + 'standalone/',
            anythingslider  : jquery + 'anythingslider/',
            blockui         : jquery + 'blockui/',
            contextmenu     : jquery + 'contextmenu/',
            daterange       : jquery + 'daterange/',
            dynatree        : jquery + 'dynatree/',
            fancybox        : jquery + 'fancybox/',
            fgmenu          : jquery + 'fgmenu/',
            highcharts      : jquery + 'highcharts/',
            imgareaselect   : jquery + 'imgareaselect/',
            multiselect     : jquery + 'multiselect/',
            swfupload       : jquery + 'swfupload/',
            timeentry       : jquery + 'timeentry/',
            tipsy           : jquery + 'tipsy/',
            treeview        : jquery + 'treeview/',
            wysiwyg         : jquery + 'wysiwyg/',
            zclip           : jquery + 'zclip/',
            ui              : jquery + 'ui/'
        }
    };
    return paths;
}(root));

/*
 * jQuery selector shortcut
 *
 * @param: selector / string or object / DOM selector
 */
var jQ = function (selector) {
    return jQuery(selector) || jQuery('#' + selector) || jQuery('input[name=' + selector + ']');
};

/*
 * does the element exists or not
 *
 * @param: selector / string or object / DOM selector
 */
var exist = function (selector) {
    return 0 === jQ(selector).length ? false : true;
};

/*
 * jQuery ui - dialog(Modal)
 */
var jModal = (function () {
    return {

        /*
         * close modal
         */
        close: function () {
            jQ('#modal').dialog('destroy');
        },

        /*
         * display modal
         *
         * @param: msg / string / message for display
         * @param: title / string / title of dialog
         * @param: ok / json object / click button
         * @param: close / json object or string / close button or text
         */
        show: function (msg, title, ok, close) {
            var dialogTitle = 'string' === typeof (title) ? title : '發生錯誤';
            var btn = [{
                    text: '關閉',
                    click: function () {
                        jQ(':submit,:button').removeProp('disabled');
                        jQ(this).dialog('close');
                    }
                }];
            var modal = jQ('#modal');

            if ('undefined' !== typeof (close)) {
                if ('string' === typeof (close)) {
                    btn[0].text = close;
                }
                if ('string' === typeof (close.text) && 'function' === typeof (close.click)) {
                    btn.push(close);
                }
            }

            if ('undefined' !== typeof (ok)) {
                if ('string' === typeof (ok.text) && 'function' === typeof (ok.click)) {
                    btn.unshift(ok);
                }
            }

            modal.html(msg.replace(/\n/gi, '<br />')).dialog('destroy');
            modal.dialog({
                draggable: false,
                resizable: false,
                modal: true,
                title: dialogTitle,
                buttons: btn
            });
        }
    };
}());

/*
 * module class
 */
var module = (function () {

    'use strict';

    var p = path.plugin;

    jQuery.lazy({src: p.anythingslider + 'jquery.anythingslider.min.js', name: 'anythingSlider', dependencies: {
        css: [p.anythingslider + 'anythingslider.css']
    }, cache: true});
    jQuery.lazy({src: p.tipsy + 'jquery.tipsy.js', name: 'tipsy', dependencies: {css: [p.tipsy + 'jquery.tipsy.css']}, cache: true});
    jQuery.lazy({src: p.timeentry + 'jquery.timeentry.js', name: 'timeEntry', dependencies: {css: [p.timeentry + 'jquery.timeentry.css']}, cache: true});
    jQuery.lazy({src: p.s + 'jquery.alphanumeric.js', name: 'numeric', cache: true});
    jQuery.lazy({src: p.s + 'twzipcode-1.4.js', name: 'twzipcode', cache: true});

    //jQuery ui - autocomplete
    jQuery.lazy({src: p.ui + 'jquery.ui.autocomplete.min.js', name: 'autocomplete', cache: true});

    //jquery-ui daterangepicker
    jQuery.lazy({src: p.daterange + 'daterangepicker.jQuery.js', name: 'daterangepicker', dependencies: {
        css: [
            path.css + 'jquery-ui.css',
            p.daterange + 'ui.daterangepicker.css'
        ]
      }, cache: true}
    );

    //jQuery.lazy({src:p.treeview + 'jquery.treeview.js', name: 'treeview', dependencies:{css: [p.treeview + 'jquery.treeview.css']}, cache:true});
    jQuery.lazy({src: p.fgmenu + 'fg.menu.js', name: 'menu', dependencies: {
        css: [
            p.ui + 'jquery-ui-smoothness.css',
            p.fgmenu + 'fg.menu.css'
        ]
    }, cache: true});

}());

/*
 * customize jQuery extend
 */
//serializeJSON
(function ($) {

    var _escape = function (name) {
        var result  = name.replace(/\[/, '\\[');
        return result.replace(/\]/, '\\]');
    };

    $.fn.serializeJSON = function (onlyValue) {
        var json = {}, name = '';
        jQuery.map($(this).serializeArray(), function(n, i) {
            if (true === onlyValue) {
                json[n['name']] = n['value'];
            }
            else {
                name = _escape(n['name']);
                if (0 < jQuery(name).length) {
                    json[n['name']] = jQuery(name);
                }
                else if (0 < jQuery('#' + name).length) {
                    json[n['name']] = jQuery('#' + n['name']);
                }
                else if (0 < jQuery('.' + name).length) {
                    json[n['name']] = jQuery('.' + name);
                }
                else if (0 < jQuery('input[name=' + name + ']').length) {
                    json[n['name']] = jQuery('input[name=' + name + ']');
                }
                else if (0 < jQuery('select[name=' + name + ']').length) {
                    json[n['name']] = jQuery('select[name=' + name + ']');
                }
                else if (0 < jQuery('textarea[name=' + name + ']').length) {
                    json[n['name']] = jQuery('textarea[name=' + name + ']');
                }
                else {
                    json[n['name']] = {};
                }
            }
        });
        return json;
    };

    // implement JSON.stringify serialization
    JSON.stringify = JSON.stringify || function (obj) {
        var t = typeof (obj);
        if (t != "object" || obj === null) {
            // simple data type
            if (t == "string") {
                obj = '"'+obj+'"';
            }
            return String(obj);
        }
        else {
            // recurse array or object
            var n, v, json = [], arr = (obj && obj.constructor == Array);
            for (n in obj) {
                if (obj.hasOwnProperty(n)) {
                    v = obj[n]; t = typeof(v);
                    if (t == "string") v = '"'+v+'"';
                    else if (t == "object" && v !== null) v = JSON.stringify(v);
                    json.push((arr ? "" : '"' + n + '":') + String(v));
                }
            }
            return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
        }
    };

}(jQuery));

/*
 * home class
 */
var home = function () {

    'use strict';

    (function () {
        if (jQuery.isFunction(jQuery.blockUI)) {
            jQuery(document).ajaxStop(
                function () {
                    jQuery.unblockUI();
                }
            );
        }
    }());
    
    /*
     * jQuery - timeentry setting
     */
    (function () {
        if (exist('input.timeentry')) {
            jQ('input.timeentry').timeEntry({show24Hours: true});
        }
    }());

    /*
     * jQuery - datepicker setting
     */
    (function () {
        if (exist('input.singledd')) {
            jQ('input.singledd').datepicker({
                dateFormat: 'yy-mm-dd',
                changeMonth: true,
                changeYear: true,
                minDate: '2011-01-01',
                maxDate: '+3Y'
            });
        }
    }());
    
    /*
     * jQuery - fancybox
     */
    (function () {
        jQ('a.fancybox').fancybox({
            titlePosition: 'over'
        });
    }());
    
    /*
     * jQuery - tipsy setting
     */
    (function () {
        jQ('a.tipsy,span.tipsy,div.tipsy,input.tipsy').tipsy({gravity: 's', live: true});
    }());

    /*
     * jQuery alphanumeric
     */
    (function () {
        jQ('input.int, input.numeric, input.digital').numeric();
        jQ('input.int-minus').numeric({allow: '-'});
    }());
    
    /*
     * jQuery autocomplete
     */
    (function () {
        //jQuery ui - autocomplete
        jQuery.lazy({src: path.plugin.ui + 'jquery.ui.autocomplete.min.js', name: 'autocomplete', dependencies:{
            js: [path.plugin.ui + 'jquery-ui-full.js'],
            css: [path.plugin.ui + 'jquery-ui-blitzer.css']
        }, cache: true});

        var input = jQ('input[name=term][id=term]');
        
        var options = {
            source: path.ajax + 'Search',
            select: function (e, ui) {
                if (ui.item) {
                    input.val(ui.item.value);
                    jQ('#search').submit();
                }
            }
        };
        
        //autocomplete
        input.autocomplete(options);
        
        jQ('#search').delegate('a[id=submit]', 'click', function () {
                jQ('#search').submit();
        });
        
    }());
    
    /*
     * tab control
     */
    (function () {

        var panel = (location.hash || '').replace(/^#/, '');
        var prefix = '#panel-';
        var url = location.href.toLowerCase();

        if (exist(prefix + panel)) {
            jQuery('div.tabs').hide();
            jQuery('a[href*=#], a.tab').removeClass('selected');
            jQuery('a[href*=#' + panel + ']').addClass('selected');
            jQuery(prefix + panel).show();
        }

        jQuery('body').delegate('a[href*=#]', 'click', function () {
            var obj = jQuery(this);
            var href = obj.attr('href');
            var rel = (obj.attr('rel') || '').toString().toLowerCase();
            var pos = href.indexOf('#');
            var hash = href.substring(pos, href.length);
            var target = hash.replace(/^#/, '');


            if (-1 === url.indexOf(rel)) {
                location.href = href;
                return false;
            }

            if (-1 === pos) {
                location.href = href;
                return false;
            }

            if (0 === target.length) {
                return;
            }

            jQuery('div.tabs').hide();
            jQuery('a[href*=#]').removeClass('selected');
            jQuery('a[href*=' + hash + ']').addClass('selected');
            jQuery(prefix + target).show(0, function() {
                jQuery(window).resize();
            });
            location.hash = target;
            return false;
        });
        
    }());
    
    /*
     * linkAction
     */
    (function () {

        jQ('a.external').click(function () {
            window.open(jQ(this).attr('href'), '_blank');
            return false;
        });

        jQ('a.back,button.back,input.back').click(function () {

                var obj = jQ(this);

                if ('undefined' !== typeof obj.val()) {
                    if (0 !== obj.val().length) {
                        location.href = obj.val();
                    }
                    else {
                        history.back();
                    }
                }
                else {
                    history.back();
                }
                return false;
            }
        );

    }());
    
    /*
     * category sidebar
     */
    (function () {
        /*
         * category list initialize
         * adjust position for selected item and remove linkable for lv2-category
         */
        if (exist('ul.category-list')) {
            var category = jQ('ul.category-list');
            category.children('li:first').addClass('first').siblings().addClass('first');
            jQuery.fn.exchangePositionWith = function (selector) {
                if (0 < jQ(this).length) {
                    var other = jQuery(selector);
                    this.after(other.clone());
                    other.after(this).remove();
                }
            };
            if (!category.hasClass('search')) {
                category.find('li.selected').parent('ul').parent('li').exchangePositionWith('ul.category-list li:eq(0)'); //move to first position                
                jQ('ul.category-list').find('li.first > a').contents().unwrap().wrap('<span class="sub" />'); //remove sub-category link
                jQ('input[type=hidden][name=category]').val(category.find('li.selected').children('a:first').attr('rel'));
            }
        }
    }());
    
    (function () {
        var msg = jQuery('.float-message');
        msg.animate({'opacity': 1}, 3000, function () {
            jQuery(this).fadeOut();
        });
    }());
    
    /*
     *
     */
    (function () {
        //float cart
        if (exist('#cart')) {
            var cart = jQ('#cart');
            jQuery.lazy({src: path.plugin.s + 'jquery.floatobject-1.4.js', name: 'makeFloat', cache: true});
            cart.makeFloat({x: 'current', y: 'current', speed: 'fast'});
            cart.children('ul.header').delegate('span', 'click', function () {
                cart.slideUp();
            });
        }
        
        jQ(':text').focus();
        
    }());
};

/*
 * cookie cart class
 */
var cart = (function () {

    //fetch cookies of item and quantity
    var cartid  = null === web.cookie.get('_cartid') ? [] : web.cookie.get('_cartid').split(',');
    var cartqty = null === web.cookie.get('_cartqty') ? [] : web.cookie.get('_cartqty').split(',');
    var additcartid  = null === web.cookie.get('_additcartid') ? [] : web.cookie.get('_additcartid').split(',');
    
    var refresh = function (result) {
        //try {
            if (result.data) {
                var length = result.data.length, qty = 0, price = 0;
                var data = result.data;
                var cart = jQ('#cart > #item');
                for (var i=0; i<length; i++) {
                    qty += data[i].qty;
                    price += (data[i].qty * data[i].price);
                }
                cart.children('li.qty:first').children('span').text(qty);
                cart.children('li.price:first').children('span').text(price.toString().comma());
            }
            jQuery.unblockUI();
            /*
        }
        catch (e) {
        }
        */
    };
    
    //updating carts
    var update = function () {
        web.cookie.set('_cartid', cartid.toString(), 0, '/', domain);
        web.cookie.set('_cartqty', cartqty.toString(), 0, '/', domain);
        web.cookie.set('_additcartid', additcartid.toString(), 0, '/', domain);
    };
    
    return {
        /*
         * initialize checked and selected elements from the cart
         */
        init: function () {
            var i = 0, len = cartid.length;
            for (i=0; i<len; i++) {
                jQ('input[type=checkbox][name=addition_id\\[\\]][value=' + cartid[i] + ']').prop('checked', true);
                jQ('select[name=addition_qty\\[\\]] option[value=' + cartqty[i] + ']').prop('selected', true);
            }
            jQ('select[name=qty] option[value=' + cartqty[len - 1] + ']').prop('selected', true);
            
            jQuery.ajax({
                url: path.ajax + 'Cart',
                type: 'POST',
                dataType: 'JSON',
                cache: false,
                success: refresh
            });
        },
        
        /*
         * refresh floating cart (ajax success handler)
         * call the private function
         */
        refresh: function (result) {
            refresh(result);
        },
        
        /*
         * cart ajax updating
         */
        submit: function (func, showname) {
            jQuery.blockUI({message: null});
            jQuery.ajax({
                url: path.ajax + 'AddtoCarts',
                type: 'POST',
                data: {ct: jQ('input[type=hidden][name=ct]').val(), showname: showname || ''},
                dataType: 'JSON',
                success: func || refresh
            });
        },
        
        // add item to the cart
        add: function (id, qty, addit) {
            
            if (addit) {
                additcartid.push(id);
                jQuery.unique(additcartid); //jQuery unique
            }
            
            var exist = cartid.find(id);
            if (false !== exist) {
                cartqty[exist] = qty.toString().intval();
            }
            else {
                cartid.push(id);
                cartqty.push(qty.toString().intval());
            }
            update();
        },
        
        //remove item and qty from the cart
        del: function (id) {
            
            var exist = cartid.find(id);
            if (false !== exist) {
                cartid.remove(exist);
                cartqty.remove(exist);

                var addit_exist = additcartid.find(id);

                if (false !== exist) {
                    additcartid.remove(exist);
                }
            }
            update();
        }
    };
}());

/*
 * binding onload
 */
jQuery(function () {
    'use strict';
    home();
});

