//专题添加
var PageSize = 20;//每页计数
var CurrentPage = 1; //当前页
var keyword = '';
var catID = '0';
var brandID = '0';
var searchType = '0';
var status = 0;//刚进入页面不要列出商品,点击"添加商品"后再获取列表
var showadv = 0;//高级搜索显示状态

//列表查询条件
var search_urldata = 'type=ajax&Action=SearchProductsAjax&keyword=' + escape(keyword) + '&CatID=' + catID + '&BrandIDs=' + brandID + '&SearchType=' + searchType + '&PageSize='+PageSize+'&Page='+CurrentPage;
$(document).ready(function(){
    
    //loading
    $('#loadingContainer').ajaxStart(function(){$(this).show();$('#loadingbackground').show().css({"opacity": "0.5"});}).ajaxStop(function(){$(this).hide();});
	var isIE6 = ($.browser.msie && $.browser.version=='6.0'); 
    setInterval(function(){
        $('div.sub_container_content').css('height',$(window.parent.frames.right).height()-$('div.sub_container_title').height()); //设置内容区域的高度
        
        if(isIE6){
            $('#datacontainer').css('height','390px');
        }else{
            $('#content').css('height',$('#popupContact').height()-$('#popupHead').height());
            $('#datacontainer').css('height',$('#content').height()-$('#sub_container_listhead').height()-$('#pageDataList1_Pager').height()-$('#divsave').height()-60);
        };
        
        
    },1000);
    
    /*调整编辑框大小开始*/
    $('#ftbdescription_addwidth').click(function(){ReSize($('#ftbDescription_editor'),'width',true,20);});
    $('#ftbdescription_addheight').click(function(){ReSize($('#ftbDescription_editor'),'height',true,20);});
    $('#ftbAD_addwidth').click(function(){ReSize($('#ftbAD_editor'),'width',true,20);});
    $('#ftbAD_addheight').click(function(){ReSize($('#ftbAD_editor'),'height',true,20);});
    $('#ftbContent_addwidth').click(function(){ReSize($('#ftbContent_editor'),'width',true,20);});
    $('#ftbContent_addheight').click(function(){ReSize($('#ftbContent_editor'),'height',true,20);});
    /*调整编辑框大小结束*/
    
    $('input[@name^=sort_]').blur(function(){
        CheckSort($(this));
    });
    $('input[@name=chkAll]').click(function(){$('input[@name=chkItem]').attr('checked',$(this).attr('checked'));});//全选
    
    $('#sel_category option').eq(0).attr('selected','selected');
    $('#sel_category').change(function(){
        var categoryIDs = $(this).val();
        if(categoryIDs == null){return false;};
        $.ajax({
            url:'ZhuanMaiAdd.aspx?type=ajax&Action=GetBrandByCatID&product_category_id='+categoryIDs + '&NoCopyRight=1',
            cache:false,
            success:function(data){if(!checkLoginStatus(data)){return false;};$('#sel_brand').html(data);$('#sel_brand option').eq(0).attr('selected','selected');},
            error:function(){alert('error');}
        });
    });
    
    $('#btnAddCat').click(function(){
        var currObj = $(this);
        //创建模板临时ID
        if(currObj.data('catID')){
            currObj.data('catID',currObj.data('catID')+1);
        }else{
            currObj.data('catID',1);
        };
        var index = currObj.data('catID');
        var template = $('#cattemplate').clone().show().attr('id','cattemplate_' + index);
        template.find('#CatProductIDs').attr('id','CatProductIDs_'+index).attr('name','CatProductIDs_'+index);
        template.find('[@name=txtCatName]').attr('name','txtCatName_'+index);
        template.find('[@name=catID]').attr('name','catID_'+index);
        template.find('#btnShowPop').attr('id','btnShowPop_'+index).click(function(){
            $('#btnSubmit').data('catID',index);//记录catID,根据catID来判断是给哪个类别添加商品
            showPopup();
        });
        template.find('#btnShowUpload').attr('id','btnShowUpload_'+index).click(function(){
            $('#uploadContent').popup({width:'80%',height:'80%',popupHead:'uploadHead',btnClose:'uploadClose'});
        });
        template.find('#DelCat').attr('id','DelCat_'+index).click(function(){
            template.remove();
        });
        currObj.before(template);
    });
    
    //搜索
    $('#btnSearch').click(function(){
        CurrentPage = 1;
        keyword = $('#txtKeyword').val();
        catID = $('#sel_category').val();
        brandID = $('#sel_brand').val();
        if(catID == null){catID = '0'};
        if(brandID == null){brandID = '0';}
        searchType = $('#sel_searchType').val();
        search_urldata = 'type=ajax&Action=SearchProductsAjax&keyword=' + escape(keyword) + '&CatID=' + catID + '&BrandIDs=' + brandID + '&SearchType=' + searchType + '&PageSize='+PageSize+'&Page='+CurrentPage;
        BindProducts('SearchProduct.aspx',search_urldata)
        if(showadv == 1){
            $('#showadvsearch').click();
        }
    });
    
    //显示隐藏高级搜索
    $('#showadvsearch').toggle(function(){
	    $('#advsearch').show();$('#showadvsearch').text('简易搜索');showadv = 1;
	},function(){
	    $('#advsearch').hide();$('#sel_category').val('0');$('#sel_brand').val('0');$('#showadvsearch').text('高级搜索');showadv = 0;
	});
	
	//如果是修改,绑定数据后给控件绑定事件
	if(getQueryStringRegExp('ID') != ''){
	    BindEvent();
	};
	
	//选择商品后点击确认
	$('#btnSubmit').click(function(){
        var productIDs = '';
        var selectedPIDs = '';
        var tempCatID = $(this).data('catID');
        var objCatContainer = $('#cattemplate_'+tempCatID);
        var objPIDs = $('#CatProductIDs_'+tempCatID);//记录当前类别下选择的商品ID的控件
        if(objPIDs.val() != ''){
            selectedPIDs = ','+objPIDs.val()+',';
        };
        $('input[@name=chkItem][@checked]').each(function(){
            var currobj = $(this);
            if(selectedPIDs.indexOf(',' + currobj.val() + ',') == -1){
                var productname = currobj.parent().siblings('#Name').text();
                var productno = currobj.parent().siblings('#ProductNo').text();
                var row = $('<tr><td class="delete"><img src="images/x-gray.gif" alt="删除" /><input type="hidden" name="pid" value=' + currobj.val() + '></td><td>' + productname + '</td><td>' + productno + '</td><td><input type="text" class="inputstyle" size="9" maxlength="10" name="sort_"'+tempCatID+' value="'+ currobj.val() +'" /></td></tr>');
                row.find('.delete').css('cursor','pointer').click(function(){
                    $(this).parent().remove();
                    var ids = '';
                    $('input[@name=pid]',objCatContainer).each(function(){
                        ids += $(this).val() + ',';
                    });
                    if(ids != ''){ids = ids.substring(0,ids.length-1);};
                    objPIDs.val(ids);
                }).find('img').mouseover(function(){
                    $(this).attr('src','images/x-red.gif');
                }).mouseout(function(){
                    $(this).attr('src','images/x-gray.gif');
                });
                row.find('input[@name^=sort_]').blur(function(){
                    CheckSort($(this));
                });
                $('.listresult',objCatContainer).append(row);
                productIDs += currobj.val() + ',';
            };
        });//end each
        if(productIDs != ""){
            productIDs = productIDs.substring(0,productIDs.length-1);
            objPIDs.val(objPIDs.val() + (objPIDs.val() != '' ? ',' : '') + productIDs);//隐藏控件记录已选择的商品ID(逗号分隔1,2,3)
        };
        $('#popupContactClose').click();//关闭层
        
    });//end click
    
    //保存
    $('#btnSave').click(function(){
        $('[@id^=cattemplate_]').each(function(index,n){
            $(this).find('[@name^=txtCatName_]').attr('name','txtCatName_'+index);
            $(this).find('[@name^=CatProductIDs_]').attr('name','CatProductIDs_' + index);
            $(this).find('[@name^=catID_]').attr('name','catID_' + index);
            $(this).find('[@name^=sort_]').attr('name','sort_' + index);
        });
        $('#hidden_CatNum').val($('[@id^=cattemplate_]').length);//记录个数
    });
    
    //预览
    $('#btnPreview').click(function(){
        var objpreform = $('#formpreview');
        objpreform.html('');
        objpreform.append('<input type="hidden" name="pre_title" value="' + escape($('#txtTitle').val()) + '" />');
        objpreform.append('<input type="hidden" name="pre_description" value="' + escape($('#ftbDescription').val()) + '" />');
        objpreform.append('<input type="hidden" name="pre_ad" value="' + escape($('#ftbAD').val()) + '" />');
        objpreform.append('<input type="hidden" name="pre_style" value="' + ($('#txtStyle').val()) + '" />');
        objpreform.append('<input type="hidden" name="pre_tempFolder" value="' + ($('#tempFolder').val()) + '" />');
        var catNum = 0;
        $('[@id^=cattemplate_]').each(function(index,n){
            objpreform.append('<input type="hidden" name="pre_CatName_' + index + '" value="' + escape($(this).find('[@name^=txtCatName_]').val()) + '" />');
            objpreform.append('<input type="hidden" name="pre_CatProductIDs_' + index + '" value="' + $(this).find('[@name^=CatProductIDs_]').val() + '" />');
            catNum += 1;
        });
        objpreform.append('<input type="hidden" id="hidden_pre_CatNum" name="hidden_pre_CatNum" value="' + catNum + '" />');
        objpreform.submit();
    });
    
    //关闭页面时删除临时文件夹
    $(window).unload(function(){
        if(getQueryStringRegExp('ID') == ''){
            $.ajax({url:'ZhuanMaiAdd.aspx?type=ajax&Action=DeleteTempFolder&folder='+escape($('#tempFolder').val())});
        };
    });
    
});// end ready

function BindEvent(){
    $('[@id^=cattemplate_]').each(function(index){
        var template = $(this);
        var productIDs = '';
        var selectedPIDs = '';
        var tempCatID = $(this).data('catID');
        var objPIDs = template.find('[@id^=CatProductIDs_]');//记录当前类别下选择的商品ID的控件
        if(objPIDs.val() != ''){
            selectedPIDs = ','+objPIDs.val()+',';
        };
        template.find('#btnShowPop_'+index).click(function(){
            $('#btnSubmit').data('catID',index);//记录catID,根据catID来判断是给哪个类别添加商品
            showPopup();
        });
        template.find('#btnShowUpload_'+index).click(function(){
            $('#uploadContent').popup({width:'80%',height:'80%',popupHead:'uploadHead',btnClose:'uploadClose'});
        });
        template.find('#DelCat_'+index).click(function(){
           template.remove();
        });
        template.find('.listresult tr:gt(0)').each(function(){
            $(this).find('.delete').css('cursor','pointer').click(function(){
                $(this).parent().remove();
                var ids = '';
                $('input[@name=pid]',template).each(function(){
                    ids += $(this).val() + ',';
                });
                if(ids != ''){ids = ids.substring(0,ids.length-1);};
                objPIDs.val(ids);
            }).find('img').mouseover(function(){
                $(this).attr('src','images/x-red.gif');
            }).mouseout(function(){
                $(this).attr('src','images/x-gray.gif');
            });
        });
        
    });
    $('#btnAddCat').data('catID',$('[@id^=cattemplate_]').length);//记录个数
};// end BindEvent

function showPopup(){
    $('#popupContact').popup({width:'80%',height:'80%',popupHead:'popupHead',btnClose:'popupContactClose'});
    CurrentPage = 1;
    keyword = $('#txtKeyword').val();
    catID = $('#sel_category').val();
    brandID = $('#sel_brand').val();
    if(catID == null){catID = '0'};
    if(brandID == null){brandID = '0';}
    searchType = $('#sel_searchType').val();
    search_urldata = 'type=ajax&Action=SearchProductsAjax&keyword=' + escape(keyword) + '&CatID=' + catID + '&BrandIDs=' + brandID + '&SearchType=' + searchType + '&PageSize='+PageSize+'&Page='+CurrentPage;
    if(status == 0){BindProducts('SearchProduct.aspx',search_urldata);status = 1;};//如果是第一次弹出层,要获取商品列表,否则只需要显示层即可
};

//绑定数据
function BindProducts(weburl,urldata){
    $('#template').hide();//将第一行模板隐藏
    $.ajax({
        type:"get",
        dataType:"json",
        url:weburl+'?NoCopyRight=1',
        data:urldata,
        cache:false,
        success:function(msg){
            $('input[@name=chkAll]').attr('checked','');
            $('tr:gt(0)','#datas').remove();
            var data = msg.Product;
            $.each(data,function(i,n){
                var row = $('#template').clone();
                row.show().mouseover(function(){$(this).addClass('on')}).mouseout(function(){$(this).removeClass('on')}); //将复制的行显示出来并添加样式
                row.find('#checkbox').html('<input type="checkbox" name="chkItem" value="' + n.ProductID + '" />');//checkbox
                row.find('#Name').html('<a href="Show.aspx?PID=' + n.ProductID + '" target="_blank">'+n.ProductName+'</a>'); //商品名称
                row.find('#ProductNo').text(n.ProductNo);   //编码
                var categoryname = (n.CategoryID != 0 ? $('#sel_category option[@value=' + n.CategoryID + ']').text().replace('├','') : "");
                var brandname = (n.BrandID != 0 ? $('#sel_brand option[@value=' + n.BrandID + ']').text() : "");
                row.find('#Category').text(categoryname);//商品类别
                row.find('#Brand').text(brandname);//商品品牌
                row.find('#MemberPrice').text(Number(n.MemberPrice).toFixed(2))//两位小数
                row.find('#MarketPrice').text(Number(n.MarketPrice).toFixed(2))//两位小数
                row.find('#Image').text(n.ThumbnailImg)//图片
				row.attr("id","ready_" + n.ProductID);//改变绑定好数据的行的id
				row.appendTo("#datas");//添加到模板的容器中
            });
           
            //分页
            $('.sub_container_page').show();
            var pagerStyle = "flickr";//jPagerBar样式
            ShowPageBar("pageDataList1_Pager",//[containerId]
               "Products.aspx",//[url]
               {style:pagerStyle,mark:"pageDataList1Mark",
               totalCount:msg.totalCount,showPageNumber:3,pageCount:PageSize,currentPageIndex:CurrentPage,noRecordTip:" 没有记录",preWord:"上一页",nextWord:"下一页",
               onclick:"CurrentPage={pageindex};BindProducts('SearchProduct.aspx','type=ajax&Action=SearchProductsAjax&keyword=" + escape(keyword) + "&CatID=" + catID + "&BrandIDs=" + brandID + "&SearchType=" + searchType + "&PageSize=" + PageSize + "&Page={pageindex}');return false;"}//[attr]
            );
            
        },//end success
        error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!')}else{alert(textStatus)};}
    });//end ajax
}//end funciton


function checkLoginStatus(data){
    var result = true;
    if(data.indexOf('<!DOCTYPE') != -1){
        result = false;
        alert('身份已过期,请重新登陆!');
    }
    return result;
};

function ReSize(objContainer,direction,isAdd,size){
    if(direction == 'width'){
        if(isAdd){
            objContainer.width(objContainer.width()+size);
        }else{
            objContainer.width(objContainer.width()-size);
        };
    }else{
        if(isAdd){
            objContainer.height(objContainer.height()+size);
        }else{
            objContainer.height(objContainer.height()-size);
        };
    };
};

function CheckSort(obj){
	var reg = new RegExp(/\D/g);
	if(reg.test(obj.val()) || obj.val().Trim() == ''){
	    alert('排序填写错误');
	    obj.focus();
	};
}