var ShoppingForContent = function()
{
    this.idShoppingProducts = 'shoppingproducts';
    this.idShoppingBrands = 'shoppingbrands';
    this.idShoppingGroups = 'shoppinggroups';
    this.idTabShopping = 'tabshopping';
    this.idTabTools = 'tabtools';
    this.getContent = false;
    this.cache = {groups:{},brands:{}};
    this.groups = {};
    this.brands = {};
    this.webSiteUrl = '';
}
/*** init method ***/
ShoppingForContent.prototype.init = function(params)
{
    this.webSiteUrl = params.websiteurl ? params.websiteurl : '';
}
/*** method returns object for work ajax ***/
ShoppingForContent.prototype.getXMLHttpRequest = function()
{
    try {return new XMLHttpRequest();}
    catch (e) {
        try {return new ActiveXObject("Msxml2.XMLHTTP");}
        catch (e) {
            try {return new ActiveXObject("Microsoft.XMLHTTP");}
            catch (e) {return null;}
        }
    }
}
/*** method shows tab for shopping ***/
ShoppingForContent.prototype.tabForContent = function()
{
    var tabTools = document.getElementById(this.idTabTools);
    var linkToObject = this;
    if (tabTools == null) {return;}
    var children = tabTools.childNodes;
    for (var i=0; i<children.length; i++) {
        if (children.item(i).nodeName == 'SPAN') {
            children.item(i).addEventListener('click', function(){
                var elmParent = this.parentNode.childNodes;
                for (var j=0; j<elmParent.length; j++) {
                    if (elmParent.item(j).nodeName == 'SPAN' && elmParent.item(j).className == 'active') {
                        elmParent.item(j).removeAttribute('class');
                    }
                }
                var v = this.innerHTML.toLowerCase();
                if (v == 'shopping') {
                    if (linkToObject.getContent == true) {
                        document.getElementById(linkToObject.idTabShopping).style.display = 'block';
                    } else {
                        var req = linkToObject.getXMLHttpRequest();
                        if (req != null) {
                            req.open('POST', linkToObject.webSiteUrl+'sys/backend_container/getgroupsandbrands/', true);
                            req.onreadystatechange = linkToObject.handlerTabForContent;
                            req.onreadystatechange = function() {
                                if (req.readyState == 4) {
                                    if (req.status == 200) {
                                        var obj = eval('('+req.responseText+')');
                                        var groups = document.getElementById(linkToObject.idShoppingGroups);
                                        if (groups != null && obj.groups != '') {
                                            groups.innerHTML = obj.groups;
                                        }
                                        var brands = document.getElementById(linkToObject.idShoppingBrands);
                                        if (brands != null && obj.brands != '') {
                                            brands.innerHTML = obj.brands;
                                        }
                                        document.getElementById(linkToObject.idTabShopping).style.display = 'block';
                                        linkToObject.getContent = true;
                                    } else {
                                        document.getElementById(linkToObject.idTabShopping).style.display = 'block';
                                    }
                                }
                            }
                            req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                            req.setRequestHeader('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT');
                            req.setRequestHeader('Pragma', 'no-cache');
                            req.send(null);
                        }
                    }
                } else {
                    document.getElementById(linkToObject.idTabShopping).style.display = 'none';
                }
                this.setAttribute('class', 'active');
            }, false);
        }
    }
}
/*** handler ***/
ShoppingForContent.prototype.getProducts = function(elm)
{
    var pair = elm.name.split('-');
    var f = pair[0] != '' ? pair[0] : '';f = f.replace(/^\s+/g,'');f = f.replace(/\s+$/g,'');
    var v = pair[1] != '' ? pair[1] : '';v = v.replace(/^\s+/g,'');v = v.replace(/\s+$/g,'');
    switch (f) {
        case 'group':
            if (elm.checked == true) {
                this.addProductsForGroup(v);
            } else {
                for (var g in this.groups) {
                    if (g == v) {
                        delete this.groups[g];break;
                    }
                }
                this.showProducts();
            }
            break;
       case 'brand':
            if (elm.checked == true) {
                this.addProductsForBrand(v);
            } else {
                for (var b in this.brands) {
                    if (b == v) {
                        delete this.brands[b];break;
                    }
                }
                this.showProducts();
            }
            break;
        default:
            break;
    }
}
/*** method adds products if user selected group ***/
ShoppingForContent.prototype.addProductsForGroup = function(id)
{
    if (!/^([0-9]{1,10})$/.test(id) || id <= 0) {return;}
    for (var i in this.cache.groups) {
        if (i == id) {
            this.groups[i] = this.cache.groups[i];
            this.showProducts();return;
        }
    }
    var req = this.getXMLHttpRequest();
    if (req == null) {return;}
    req.open('POST', this.webSiteUrl+'sys/backend_container/getproductsforgrouporbrand/', true);
    var linkToObject = this;
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            if (req.status == 200) {
                var obj = eval('('+req.responseText+')');
                if (obj.length > 0) {
                    linkToObject.cache.groups[id] = obj;
                    linkToObject.groups[id] = obj;
                } else {
                    linkToObject.cache.groups[id] = {};
                }
                linkToObject.showProducts();
            }
        }
    }
    req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    req.setRequestHeader('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT');
    req.setRequestHeader('Pragma', 'no-cache');
    req.send('flag=group&id='+id);
}
/*** method adds products if user selected brand ***/
ShoppingForContent.prototype.addProductsForBrand = function(name)
{
    if (name == '') {return;}
    for (var i in this.cache.brands) {
        if (i == name) {
            this.brands[i] = this.cache.brands[i];
            this.showProducts();return;
        }
    }
    var req = this.getXMLHttpRequest();
    if (req == null) {return;}
    req.open('POST', this.webSiteUrl+'sys/backend_container/getproductsforgrouporbrand/', true);
    var linkToObject = this;
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            if (req.status == 200) {
                var obj = eval('('+req.responseText+')');
                if (obj.length > 0) {
                    linkToObject.cache.brands[name] = obj;
                    linkToObject.brands[name] = obj;
                } else {
                    linkToObject.cache.brands[name] = {};
                }
                linkToObject.showProducts();
            }
        }
    }
    req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    req.setRequestHeader('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT');
    req.setRequestHeader('Pragma', 'no-cache');
    req.send('flag=brand&name='+name);
}
/*** method generates content for products ***/
ShoppingForContent.prototype.showProducts = function()
{
    var content = '';
    var template = '<div class="shoppingproduct">';
    template += '<div class="block1"><img src="{img}" onclick="Sc.addVariableProductToContent(\'{id}\');" title="add product"/></div>';
    template += '<p class="productbrand" title="{titlebrand}">{brand}</p>';
    template += '<div class="block2"><p class="productname" title="{titlename}">{name}</p>';
    template += '<p class="productitemid" title="{titleitemid}">{itemid}</p></div></div>';
    var products = {};
    var counterGroup = 0;
    for (var g in this.groups) {
        for (var gp in this.groups[g]) {
            products[this.groups[g][gp].id] = this.groups[g][gp];
        }
        counterGroup++;
    }
    if (counterGroup == 0) {
        for (var b in this.brands) {
            for (var bp in this.brands[b]) {
                products[this.brands[b][bp].id] = this.brands[b][bp];
            }
        }
    } else {
        var countBrand = 0;
        for (var br in this.brands) {
            countBrand++;
        }
        if (countBrand  > 0) {
            var tmp = {};
            for (var product in products) {
                for (var brand in this.brands) {
                    if (products[product].brand == brand) {
                        tmp[products[product].id] = products[product];
                    }
                }
            }
            products = tmp;
        }
    }
    for (var p in products) {
        var itemContent = template.replace('{img}', this.webSiteUrl+products[p].photo);
        itemContent = itemContent.replace('{id}', products[p].id);
        itemContent = itemContent.replace('{name}', products[p].name.substr(0,8));
        itemContent = itemContent.replace('{titlename}', products[p].name);
        itemContent = itemContent.replace('{brand}', products[p].brand.substr(0,8));
        itemContent = itemContent.replace('{titlebrand}', products[p].brand);
        itemContent = itemContent.replace('{itemid}', products[p].item_id.substr(0,8));
        itemContent = itemContent.replace('{titleitemid}', products[p].item_id);
        content += itemContent;
    }
    document.getElementById(this.idShoppingProducts).innerHTML = content;
}
/*** method adds variable product in content ***/
ShoppingForContent.prototype.addVariableProductToContent = function(id)
{
    if (!/^([0-9]{1,10})$/.test(id) || id <= 0) {return;}
    $('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, '{$product:'+id+'}');
}

ShoppingForContent.prototype.addVariableProductCategory = function()
{
    var data = '';
    var elmGroups = document.getElementById('shoppinggroups').childNodes;
    for (var g = 0; g < elmGroups.length; g++) {
        if (elmGroups.item(g).nodeName == 'P' && elmGroups.item(g).childNodes.item(0).checked == true) {
            data += ':c-'+elmGroups.item(g).title;
        }
    }
    var elmBrands = document.getElementById('shoppingbrands').childNodes;
    for (var b = 0; b < elmBrands.length; b++) {
        if (elmBrands.item(b).nodeName == 'P' && elmBrands.item(b).childNodes.item(0).checked == true) {
            data += ':b-'+elmBrands.item(b).title;
        }
    }
    if (data == '') {return;}
    $('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, '{$productlist'+data+'}');
}

var Sc = new ShoppingForContent();