/*******************************************************************************
* PPfor.js 
* Depends:
*  /Common/JS/jquery.min.js
*******************************************************************************/
if (jQuery) {
    window.PP = jQuery.noConflict();
}
PP(function() {
    //Labels
    PP('[name="ppforlabel"]').loadAjaxPage();

    //Goods Buy
    PP('.goodsbuybutton').live({
        mouseover: function() {
            var button = PP(this);
            var goodskey = button.attr('goodskey');
            var goodsid = button.attr('goodsid');
            if (PP.isEmptyGuid(goodsid) && goodskey) {
                var timer = setTimeout(function() {
                    if (timer) { PP('#' + goodskey).hide(); }
                }, 1000);
                PP('#' + goodskey).hover(function() { timer = false; }, function() {
                    timer = setTimeout(function() {
                        if (timer) { PP('#' + goodskey).hide(); }
                    }, 1000);
                }).css({ left: button.position().left, top: button.position().top })
                .show();
            }
        }, click: function() {
            PP.addGoodsToCart(PP(this).attr('goodsid'));
        }
    });

    //Iframe Auto Height
    PP('iframe.autoheight').bind({
        load: function() {
            var iframe = PP(this);
            var body = iframe.contents().find('body')[0];
            if (body) {
                if (body.scrollHeight) {                   
                    iframe.height(body.scrollHeight);
                } else {
                    var maxH = 0;
                    PP('*', body).each(function() {
                        if (this.offsetHeight && this.offsetHeight > maxH) {
                            maxH = this.offsetHeight;
                        }
                    });                    
                    PP(body).height(maxH);
                    iframe.height(maxH);
                }
                setTimeout(function() { iframe.load(); }, 1000);
            }
        }
    });
});
PP.labelOptions = {
    langGuid: '00000000-0000-0000-0000-000000000000',
    menuGuid: '00000000-0000-0000-0000-000000000000',
    classGuid: '00000000-0000-0000-0000-000000000000',
    brandGuid: '00000000-0000-0000-0000-000000000000',
    imageAlbums: [],
    slideShow: {},
    cartCookies: {},
    shopping: {}
};
PP.labelServers = {
    ajaxLabelURL: '/Common/Web/GetLabelHtml.ashx',
    ajaxContentURL: '/Common/Web/GetDynamicHtml.ashx',
    ajaxFirstURL: '/Common/Web/GetFirstModelUrl.ashx',
    ajaxGoodsBuyURL: '/Common/Web/GoodsCart.ashx',
    ajaxShoppingUrl:'/Common/Web/GetProductJson.ashx'
};
PP.extend({
    isNoneModelType: function(modelType) {
        return modelType == undefined || modelType == null || typeof (modelType) != 'string' || modelType == '' || modelType.toLowerCase() === 'none';
    },
    isEmptyGuid: function(guid) {
        return guid == undefined || guid == null || guid == 0 || (typeof (guid) == 'string' && (guid === '' || guid === '00000000000000000000000000000000' || guid === '00000000-0000-0000-0000-000000000000'));
    },
    isTrue: function(bool) {
        return !(bool == undefined || bool == null || bool == false || typeof (bool) != 'string' || bool.toLowerCase() !== 'true');
    },
    format: function(source, params) {
        if (arguments.length == 1)
            return function() {
                var args = PP.makeArray(arguments);
                args.unshift(source);
                return PP.format.apply(this, args);
            };
        if (arguments.length > 2 && params.constructor != Array) {
            params = PP.makeArray(arguments).slice(1);
        }
        if (params.constructor != Array) {
            params = [params];
        }
        PP.each(params, function(i, n) {
            source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
        });
        return source;
    },
    initLabelOptions: function(options) {
        PP.extend(PP.labelOptions, options);
    },
    addSlideShow: function(id, slide) {
        if (!PP.isEmptyGuid(id)) {
            PP.labelOptions.slideShow[id] = slide || [];
        }
    },
    getSlideShow: function(id) {
        if (!PP.isEmptyGuid(id)) {
            return PP.labelOptions.slideShow[id] || [];
        } else {
            return [];
        }
    },
    goToFirstModel: function(modelGuid) {
        if (!PP.isNoneModelType(PP.labelOptions.modelType)) {
            PP.ajax({
                'type': 'GET',
                'url': PP.labelServers.ajaxFirstURL,
                'dataType': 'text',
                'data': { 'model': PP.labelOptions.modelType, 'guid': PP.labelOptions.currentGuid, 'langGuid': PP.labelOptions.langGuid },
                'success': function(url) {
                    if (typeof (url) == 'string' && url.length > 0 && url != '#') {
                        location.replace(url);
                    }
                }
            });
        }
    },
    loadDynamics: function() {
        if (!PP.isNoneModelType(PP.labelOptions.modelType)) {
            PP.ajax({
                'type': 'GET',
                'url': PP.labelServers.ajaxContentURL,
                'dataType': 'xml',
                //'async ':false,
                'data': { 'model': PP.labelOptions.modelType, 'guid': PP.labelOptions.currentGuid, 'langGuid': PP.labelOptions.langGuid },
                'success': function(xml) {
                    PP('[name="ppfordynamic"]').each(function() {
                        var objSelf = PP(this);
                        var field = objSelf.attr('field');
                        if (field) {
                            objSelf.html(PP(field, xml).eq(0).text());
                        }
                    });
                }
            });
        }
    },
    loadShopping: function() {
        if (!PP.isNoneModelType(PP.labelOptions.modelType) && !PP.labelOptions.shopping.done) {
            PP.labelOptions.shopping.done = true;
            PP.ajax({
                'type': 'GET',
                'url': PP.labelServers.ajaxShoppingUrl,
                'dataType': 'json',
                'async ': false,
                'data': { 'model': PP.labelOptions.modelType, 'productGuid': PP.labelOptions.currentGuid, 'langGuid': PP.labelOptions.langGuid },
                'success': function(json) {
                    PP.extend(PP.labelOptions.shopping, json);
                }, 'error': function(req, status) {
                    alert(status);
                }, 'complete': function() {
                    if (typeof (PP.labelOptions.shopping.loadGodosData) == 'function') {
                        PP.labelOptions.shopping.loadGodosData();
                    }
                }
            });
        }
    },
    addGoodsToCart: function(goodsid, buyNumber, fittings) {
        if (!PP.isEmptyGuid(goodsid)) {
            buyNumber = parseInt(buyNumber || '1', 10);
            if (buyNumber < 1) {
                buyNumber = 1;
            }
            if (typeof (fittings) != 'string') {
                fittings = '';
            }
            if (typeof (PP.hideCartFeedBack) == 'function') {
                PP.hideCartFeedBack();
            }
            PP.ajax({
                'type': 'POST',
                'url': PP.labelServers.ajaxGoodsBuyURL,
                'data': { 'action': 'add', 'goodsGuid': goodsid, 'buyNumber': buyNumber, 'langGuid': PP.labelOptions.langGuid, 'fittings': fittings },
                'success': function(result) {
                    if (typeof (PP.showCartFeedBack) == 'function') {
                        PP.showCartFeedBack(PP.labelOptions.cartCookies, result);
                    } else if (result) {
                        alert(result);
                    }
                }, 'error': function(XMLHttpRequest, textStatus, errorThrown) {
                    if (typeof (PP.showCartFeedBack) == 'function') {
                        PP.showCartFeedBack(PP.labelOptions.cartCookies, textStatus);
                    } else {
                        alert(textStatus);
                    }
                }
            });
        }
    },
    createServiceBox: function(themes, options) {
        if (!themes || typeof (themes) != 'string') { return; }
        if (themes == 'default') {
            if (typeof (PP.createDefaultService) == 'function') {
                PP.createDefaultService(options);
            }
        }
    },
    loadLabelResult: function(xmlHttp) {
        var result = { guid: '00000000-0000-0000-0000-000000000000', code: '', pageIndex: 0, pageCount: 0, recordCount: 0, pagerHtml: '' };
        PP.extend(result, {
            guid: PP('Guid', xmlHttp).text(),
            code: PP('Code', xmlHttp).text(),
            callBack: PP('CallBack', xmlHttp).text(),
            pageIndex: parseInt(PP('PageIndex', xmlHttp).text(), 10),
            pageCount: parseInt(PP('PageCount', xmlHttp).text(), 10),
            recordCount: parseInt(PP('RecordCount', xmlHttp).text(), 10),
            pagerGuid: PP('PagerGuid', xmlHttp).text(),
            pagerHtml: PP('PagerCode', xmlHttp).text()
        });
        return result;
    },
    doFunction: function(func, obj) {
        if (!PP.isFunction(func)) {
            if (func.indexOf('(') > -1) {
                func = func.substring(0, func.indexOf('('));
            }
            if (func) {
                func = new Function(func + '.apply(this,arguments)');
            }
        }
        if (PP.isFunction(func)) {
            try {
                func(obj);
            } catch (e) { }
        }
    }
});
PP.fn.extend({
    doCallBack: function(func) {
        PP.doFunction(func, this);
    },
    loadAjaxPage: function(pageIndex) {
        var paramData = PP.extend({}, PP.labelOptions, { 'pageIndex': pageIndex });
        PP.each(paramData, function(n, i) {
            if (!(typeof (i) == 'string' || typeof (i) == 'number' || typeof (i) == 'boolean')) {
                paramData[n] = undefined;
            }
        });
        this.each(function() {
            var label = PP(this).html('<img src="/Common/Web/Images/loading.gif" />');
            var url = PP.labelServers.ajaxLabelURL;
            var data = PP.extend({}, paramData, { 'labelGuid': label.attr('lblguid'), 'nocache': label.attr('nocache') });

            PP.ajax({
                'url': url,
                'dataType': 'xml',
                'data': data,
                'error': function() {
                    label.empty();
                }, 'success': function(xml) {
                    var result = PP.loadLabelResult(xml);
                    var callback = result.callBack || label.attr('callback') || '';
                    label.html(result.code);
                    if (!PP.isEmptyGuid(result.pagerGuid) && result.recordCount > 0) {
                        PP('[name="ppforcontrol"][lblguid="' + result.pagerGuid + '"]').each(function() {
                            var pager = PP(this);
                            pager.html(result.pagerHtml);
                            pager.find('*').each(function() {
                                var obj = PP(this);
                                if (obj.is('.pager_first')) {
                                    if (result.pageCount <= 1 || result.pageIndex <= 1) {
                                        //obj.element.style.display = 'none';
                                    } else {
                                        obj.css('cursor', 'pointer').unbind('click').click(function() {
                                            label.loadAjaxPage(1);
                                        });
                                    }
                                } else if (obj.is('.pager_prev')) {
                                    if (result.pageIndex <= 1) {
                                        //obj.element.style.display = 'none';
                                    } else {
                                        obj.css('cursor', 'pointer').unbind('click').click(function() {
                                            label.loadAjaxPage(result.pageIndex - 1);
                                        });
                                    }
                                } else if (obj.is('.pager_next')) {
                                    if (result.pageIndex >= result.pageCount) {
                                        //obj.element.style.display = 'none';
                                    } else {
                                        obj.css('cursor', 'pointer').unbind('click').click(function() {
                                            label.loadAjaxPage(result.pageIndex + 1);
                                        });
                                    }
                                } else if (obj.is('.pager_last')) {
                                    if (result.pageCount <= 1 || result.pageIndex >= result.pageCount) {
                                        //obj.element.style.display = 'none';
                                    } else {
                                        obj.css('cursor', 'pointer').unbind('click').click(function() {
                                            label.loadAjaxPage(result.pageCount);
                                        });
                                    }
                                } else if (obj.is('select.pager_select')) {
                                    obj.unbind('change').change(function() {
                                        label.loadAjaxPage(parseInt(this.value, 10));
                                    });
                                } else if (obj.is('.pager_number')) {
                                    var p = parseInt(obj.attr('page'), 10);
                                    if (p == result.pageIndex) {
                                        obj.addClass('pager_current');
                                    } else {
                                        obj.css('cursor', 'pointer').unbind('click').click(function() {
                                            label.loadAjaxPage(p);
                                        });
                                    }
                                } else if (obj.attr('page')) {
                                    var p = parseInt(obj.attr('page'), 10);
                                    obj.css('cursor', 'pointer').unbind('click').click(function() {
                                        label.loadAjaxPage(p);
                                    });
                                }
                            });
                        });
                    }
                    label.doCallBack(callback);
                }
            });
        });
    }
});

