var Ajax =
{
	call:function (url, params, callback, transferMode, responseType, asyn, quiet)
	{
	 /* *
	  * 调用此方法发送HTTP请求。
	  *
	  * @public
	  * @param   {string}    url             请求的URL地址
	  * @param   {mix}       params          发送参数
	  * @param   {Function}  callback        回调函数
	  * @param   {string}    ransferMode     请求的方式，有"GET"和"POST"两种
	  * @param   {string}    responseType    响应类型，有"JSON"、"XML"和"TEXT"三种
	  * @param   {boolean}   asyn            是否异步请求的方式
	  * @param   {boolean}   quiet           是否安静模式请求
	  */
		$.ajax({
			url:url,
			data:params,
			dataType:responseType,
			type:transferMode,
			success:callback
		});
	}
}

var sUserAgent = navigator.userAgent;
var isOpera = sUserAgent.indexOf("Opera") > -1;
var isIE = sUserAgent.indexOf("compatible") > -1 && sUserAgent.indexOf("MSIE") > -1 && !isOpera;

var golbal_keyword='';
var float_status = false; //浮动层登录是否成功
var float_login_reload = false; //浮动层是否请求刷新窗口,一般在登录成功后

 function   getoffset(e)
  {
    var   t=e.offsetTop;
    var   l=e.offsetLeft;
    while(e=e.offsetParent)
    {
      t+=e.offsetTop;
      l+=e.offsetLeft;
    }

    var   rec   =   new   Array(1);
    rec[0]     =   t;
    rec[1]   =   l;
    return   rec
  }

function popCoverDiv(div,cover_div){
   if (document.getElementById(cover_div)) {
   //如果存在遮盖层，则让其显示
   if(div=='document.body'){
   var divheight=document.body.scrollHeight+50;
   }else{
   var divheight=$('#'+div).height();
   }
	document.getElementById(cover_div).style.height=divheight;
    document.getElementById(cover_div).style.display = 'block';
   } else {
	obj=document.getElementById(div);
	if(div=='document.body'){
	var   rec   =   new   Array(1);
    rec[0]     =0;
    rec[1]   =0
	}else{
	rec=getoffset(obj);
	}
   //否则创建遮盖层
    var coverDiv = document.createElement('div');
    document.body.appendChild(coverDiv);
    coverDiv.id = cover_div;
    with(coverDiv.style) {
     position = 'absolute';
     background = '#000000';
	 if(div=='document.body'){
	var divwidth=document.body.scrollWidth;
	  var divheight=document.body.scrollHeight+50;
	 }else{
	 var divwidth=$('#'+div).width();
	  var divheight=$('#'+div).height();
	 }
	  if(isIE){
	 coverDiv.style.left = rec[1];
	 coverDiv.style.top = rec[0];
	  }else{
	  coverDiv.style.left = rec[1]+"px";
	 coverDiv.style.top = rec[0]+"px";
	  }
     width =divwidth;
     height = divheight;
     zIndex = 499;
      filter = "Alpha(Opacity=60)";//IE逆境
    }
   }
}

/*导航菜单*/
$(function(){
    _initNavigation();
	//  修改购物车数目								 );
    if( document.getElementById('cart_num') && typeof(cart_num) != 'undefined' ){
        $('#cart_num').text(cart_num);
    }
    //var a = document.setCookie('pop_cart_div',1);
    // 判断是否要弹出购物车o
    var a = document.getCookie('pop_cart_div');
    if( parseInt(a) == 1 ){
        popCart(5);
        $.scrollTo('div#my_cart',1000);
        document.setCookie('pop_cart_div',0);
    }

});
function _initNavigation(){
        $('#hd-nav>li>a').hover(function(){$(this).next('div').show();},
            function(){$(this).next('div').hide();}
            );

        $('#hd-nav>li>a').next('div').hover(function(){$(this).show();$(this).prev('a').addClass('cur');},
            function(){$(this).hide();$(this).prev('a').removeClass('cur');});

    // autocomplete
    if(document.getElementById('keyword')){
        $("#keyword").autocomplete(front_server_url+'/goods_global.php?act=moreword', {
					//autoFill: true,	//自动读取第一个
					//width: divwidth+8,
					scroll: false,
                    scrollHeight: 500,
					formatItem: function(data, i, total) {
					return '<p>'+data+'</p>';
					 }
                })
    }
    // 购物车弹出帮定
    $("#my_cart").bind('mouseover', popCart);
    $("#my_cart").bind('mouseleave', _checkClosePopup);
}


//打开ajax-load DIV层
function open_ajax_load(div,cover_div)
{//32*32
if(!document.getElementById("goods_ajax_load")) return ;
if(document.getElementById('loading_here')){
		$('#loading_here').css('display','block');
		}
	 var loginwidth=32;
	  var loginheight=32;
      var login = document.getElementById("goods_ajax_load");
      login.style.position = "absolute";
	  obj=document.getElementById(div);
	  rec=getoffset(obj);
	  var divwidth=$('#'+div).width();
	  var divheight=$('#'+div).height();
	  if(isIE){
      login.style.left = (rec[1]+rec[1]+divwidth)/2-loginwidth/2;
      login.style.top = (rec[0]+rec[0]+divheight)/2-loginheight/2;
	  }else{
	  login.style.left = (rec[1]+rec[1]+divwidth)/2-loginwidth/2+"px";
      login.style.top = (rec[0]+rec[0]+divheight)/2-loginheight/2+"px";
	  }
       login.style.display='block';

	   if(cover_div){
        popCoverDiv(div,cover_div);
	   }
        void(0);//不进行任何操作,如：<a href="#">aaa</a>
}

//关闭ajax-load DIV层
function closs_ajax_load(){
	if(document.getElementById('loading_here')){
	$('#loading_here').css('display','none');
	}
	if(document.getElementById('goods_ajax_load')){
	$('#goods_ajax_load').css('display','none');
	}
	if(document.getElementById("cover_div")){
	$('#cover_div').css('display','none');
	}
}

/**
* 复制
*/

function copyCode(id){
var testCode=$('#'+id).val();
if(copy2Clipboard(testCode)!=false){
alert("生成的代码已经复制到粘贴板，你可以使用Ctrl+V 贴到需要的地方去了哦！ ");
}
}

copy2Clipboard=function(txt){
if(window.clipboardData){
window.clipboardData.clearData();
window.clipboardData.setData("Text",txt);
}
else if(navigator.userAgent.indexOf("Opera")!=-1){
window.location=txt;
}
else if(window.netscape){
try{
   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
}
catch(e){
   alert("您的firefox安全限制限制您进行剪贴板操作，请打开’about:config’将signed.applets.codebase_principal_support’设置为true’之后重试，相对路径为firefox根目录/greprefs/all.js");
   return false;
}
var clip=Components.classes['@mozilla.org/widget/clipboard;1'].createInstance

(Components.interfaces.nsIClipboard);
if(!clip)return;
var trans=Components.classes['@mozilla.org/widget/transferable;1'].createInstance

(Components.interfaces.nsITransferable);
if(!trans)return;
trans.addDataFlavor('text/unicode');
var str=new Object();
var len=new Object();
var str=Components.classes["@mozilla.org/supports-string;1"].createInstance

(Components.interfaces.nsISupportsString);
var copytext=txt;str.data=copytext;
trans.setTransferData("text/unicode",str,copytext.length*2);
var clipid=Components.interfaces.nsIClipboard;
if(!clip)return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}else {
alert ('您所使用的的浏览器不能复制到剪贴板，请按Ctrl+C手动复制');
return false;
}
}


/**
* 热销排行
*/
function move_index_hot_goods(keyid){
		for(var i=1;i<=9;i++){
		if(i==keyid){
		$('#index_hot_goods_desk_'+i).css('display','none');
		$('#index_hot_goods_content_'+i).css('display','block');
		}else{
		$('#index_hot_goods_desk_'+i).css('display','block');
		$('#index_hot_goods_content_'+i).css('display','none');
		}
		}

}

/**
* 全选
*/
function checkboxAll(name){
var obj=document.getElementsByName(name+"[]");
	for(i=0;i<obj.length;i++)
	{
	if(obj[i].disabled==false){
	obj[i].checked=true;
	}
	}

}

function moreword(){
	if(golbal_keyword==escape($('#keyword').val())){
	return false;
	}
	golbal_keyword=escape($('#keyword').val());
	var keyword=golbal_keyword;
	if(keyword.length<1){
	if(document.getElementById('moreword')){
	$('#moreword').css('display','none');
	}
	return false;
	}
	//window.open('goods_global.html?act=moreword&keyword='+keyword+'&rnd='+new Date().getTime());
	$.ajax({
		url: 'goods_global.html',
		data: 'act=moreword&keyword='+keyword+'&rnd='+new Date().getTime(),
		type: 'GET',
		dataType: 'html',
		error: function(){
			//alert ('error');
		},
		success: function(result){
		if(result==1){
		if(document.getElementById('moreword')){
		$('#moreword').css('display','none');
		}
		}else{
			if(document.getElementById('moreword')){

				var obj=document.getElementById('keyword');
			var divwidth=$('#keyword').width();
			var divheight=$('#keyword').height();
			rec=getoffset(obj);
			var coverDiv=document.getElementById('moreword');
			coverDiv.style.left = rec[1];
			coverDiv.style.top = rec[0]+divheight;
		with(coverDiv.style) {
     position = 'absolute';
     background = '#FFFFFF';

	  if(isIE){
	 coverDiv.style.left = rec[1]-5;
	 coverDiv.style.top = rec[0]+divheight+5;
	  width =divwidth+8;
     //height = divheight;
	  }else{
	  coverDiv.style.left = rec[1]-5+"px";
	 coverDiv.style.top = rec[0]+divheight+5+"px";
	  width =divwidth+8+"px";
     //height = divheight;
	  }

     zIndex = 499;
      filter = "Alpha(Opacity=60)";//IE逆境
    }





			$('#moreword').html(result);
			$('#moreword').css('display','block');
			}
		}
		}
	});

}

var mouseleave_a_close = 1;
function _checkClosePopup(){
    setTimeout( "closeMyCartPopup()", 400 );
}
/**
 * 弹出购物车
 * v的值：event(mouseover) OR secondDisplay(add to cart)
 * var tip_value = function(v){
 *     $('#keyword').val($('#keyword').val()+'-'+v);
 * }
 */
var popCart = function(v){
    if( !document.getElementById("my_cart_popup") ) {
        var myCartPopup = document.createElement('div');
        myCartPopup.id= 'my_cart_popup';
        //myCartPopup.title= '我的购物车';
        document.body.appendChild(myCartPopup);
        $("#my_cart_popup").bind('mouseover', function(){window.mouseleave_a_close=0;});
        $("#my_cart_popup").hover(null,function(){window.mouseleave_a_close=2;_checkClosePopup();});
    }
    if( mouseleave_a_close===2 ){
		mouseleave_a_close = 0;
	}
    var myCartPopup= $("#my_cart_popup");

    var position = $("#my_cart").offset();
    position.width=$("#my_cart").width();
    position.height=15;
    var left = position.left-30;//($("#my_cart_popup").width()-position.width)/2;

    myCartPopup.css('left',left+'px');
    myCartPopup.css('top',(position.top+position.height-2)+'px');

    $('#my_cart').unbind('mouseover');
    $.getJSON(front_server_url+"/flow.html?step=get_cart_content_json&rand="+parseInt(Math.random()*1000)+"&callback=?",flow_json_back);
    myCartPopup.text( "正在载入您的购物车数据" );
    myCartPopup.css('display','block');

    //
    // v是显示时间
    if( typeof(v) == 'number' ){
        setTimeout("closeMyCartPopup()",(v*1000+500));
    }
}
function flow_json_back(data){
    $("#my_cart_popup").text('');
    var goodsCount = data.total.goods_count;
    if( goodsCount > 0 ){
        $.each(data.goods_list, function(i,item){
            var isPackage=false;
            if( parseInt(item.package_id)>0 ){
                isPackage=true;
                var imgSrc = image_server_url +'/'+ item.package_image+"_teeny.jpg";
                var id=item.package_id;
                var num = '&nbsp;x1';
                var name = item.package_name.substring(0,14);
                var price= item.package_real_amount+'元';
                var link_url = front_server_url+"/package-"+id+'.html';
            }else{
                var imgSrc = item.goods_thumb;
                var id=item.goods_id;
                var num = '&nbsp;x'+item.goods_number;
                var price= item.goods_price+'元';
                var color_id = item.color_id;
                var name = item.goods_name.substring(0,14) + '<br/>【'+item.color_name+'】'+ '【'+item.size_name+'】';
                var link_url = front_server_url+"/goods-"+id+'-'+color_id+'.html';
            }
            //alert( id+'..'+imgSrc);
            var html = "";
            html += '<div><table width="98%" border="0" cellspacing="0" cellpadding="0" style="margin-left:5px;" ><tr><td rowspan="2"  width="40"><a href="'+link_url+'" title="查看此商品"><img src="'+imgSrc+'" /></a></td><td><a href="'+link_url+'" class="goods_name" title="查看此商品">'+name+'</a></td><td style="width:85px; color:red; font-size:12px; text-align:right; " valign=middle>'+price+num+'</td></tr></table></div>';
            $('#my_cart_popup').append(html);
        });
        //显示小计
        var totalHtml = '<div style="text-align:right;border:0px solid;">共有<b style="color:red">'+data.total.goods_count+'</b>件商品'
                        +'&nbsp;&nbsp;总价格：<b class="shop_price">'+data.total.formated_goods_amount+'</b></div>';

        $('#my_cart_popup').append(totalHtml);
        $('#my_cart_popup').append('<input style="float:left;  margin-left:210px; padding-bottom:10px; margin-top:15px; display:inline;" type=image src="http://img.fclub.cn/images/btn_jinrujs.gif" onclick="window.location=\''+front_server_url+'/flow.php\';"/>');

    }else{
        $("#my_cart_popup").append(' <div style="border:none; height:30px; text-align:center;">您的购物车还没有商品！</div>');
        //$("#my_cart_popup").append('<a href="javascript:;" class="closeMyCartPopup" onclick="closeMyCartPopup();">关闭</a>');
    }
}
function closeMyCartPopup(){
    if( mouseleave_a_close !== 0 ) {
		var myCartPopup= $("#my_cart_popup");
		myCartPopup.css('display','none');
		myCartPopup.text('');
		// 购物车弹出帮定
		$("#my_cart").bind('mouseover', popCart);
        mouseleave_a_close =1; 
	}
}

/**
 * 判断用户是否已登录,如未登录弹出浮窗登录
 * options.back_url 站外登录成功后跳转的地址
 * options.func 登录成功后执行的操作（如果已登录，则直接执行该操作）
 * options.reload boolean 登录成功后是否刷新本页
 * options.user_id 如果user_id>0则直接执行func
 */
function check_login(options){
    options = $.extend({},options);
    var func = options.func||null;
    var reload = options.reload||null;
    var user_id = options.user_id||null;
    if(user_id!=null&&parseInt(user_id)>0) {(typeof func =='function')? func():eval(func);return}//如果已登录，则执行func
    var parent_dom = $("div#float_panel");
    parent_dom.html("<img src='http://img.fclub.cn/images/loading_invite.gif'");
    parent_dom.dialog({
        title:'页面载入中，请稍候...',
        minHeight:80,
        width:520,
        position:'center',
        modal: true,
        open:function(){
            float_status = false;
            $.ajax({
                url:'/user.html?act=register&is_float=1',
                data:{back_url:options.back_url||'',rnd:new Date().getTime()},
                dataType:'json',
                type:'POST',
                success:function(result){
                    if(result.has_logined==1){
                        float_status=true
                        parent_dom.dialog('close');
                    }else if(result.error==0){
                        parent_dom.html(result.content);
                        parent_dom.dialog('option','position','center');
                        parent_dom.dialog('option','title','用户登录');
                    }else{
                        alert(result.message);
                    }
                }
            });

        },
        close:function(){
            if (float_status==true) {
                float_login_reload = true;
                (typeof func =='function')?func():eval(func);
                if(reload) window.location.href=window.location.href;
                float_status=false;
            }
            parent_dom.dialog('destroy');
            parent_dom.html("<img src='http://img.fclub.cn/images/loading_invite.gif'");
        }
    });
}
function check_login_bak(options){
    options = $.extend({},options);
    var func = options.func||null;
    var reload = options.reload||null;
    var user_id = options.user_id||null;
    if(user_id!=null&&parseInt(user_id)>0) {(typeof func =='function')? func():eval(func);return}//如果已登录，则执行func
    var parent_dom = $("div#float_panel");
    parent_dom.html("<img src='http://img.fclub.cn/images/loading_invite.gif'");
    parent_dom.dialog({
        title:'页面载入中，请稍候...',
        minHeight:80,
        width:520,
        position:'center',
        modal: true,
        open:function(){
            float_status = false;
            $.ajax({
                url:'/user.html?act=check_login',
                data:{rnd:new Date().getTime()},
                dataType:'json',
                type:'POST',
                success:function(result){
                    if(result==1){
                        parent_dom.dialog('close');
                        (typeof func =='function')? func():eval(func);
                    }else{
                        parent_dom.load('/user.html?act=register&is_float=1',{
                            back_url:options.back_url||'',
                            rnd:new Date().getTime()
                            },
                        function(){
                            parent_dom.dialog('option','position','center');
                            parent_dom.dialog('option','title','用户登录');
                            });
                    }
                }
            });

        },
        close:function(){
            if (float_status==true) {
                float_login_reload = true;
                (typeof func =='function')?func():eval(func);
                if(reload) window.location.href=window.location.href;
                float_status=false;
            }
            parent_dom.dialog('destroy');
            parent_dom.html("<img src='http://img.fclub.cn/images/loading_invite.gif'");
        }
    });


}

  /*** 搜索*/
    function search_submit(){
        if($('#keyword').val()=='' || $('#keyword').val()=='从您感兴趣的开始'){
            alert ('请输入搜索关键字');
            return false;
        }
        return true;
    }

    var divTop, divLeft, divWidth, divHeight, docHeight, docWidth, objTimer,s_t_timer, h_i = 0, pageWidth=970;
    
    $(alert_cart);
    function alert_cart(){
        if(!document.getElementById("popMsg")) return false;
        divHeight = parseInt(document.getElementById("popMsg").offsetHeight, 10);
        divWidth = parseInt(document.getElementById("popMsg").offsetWidth, 10);        
        alert_time = parseInt(alert_time);
        //getMsg();
        if (typeof (alert_time) != 'undefined' && alert_time>0)
        {
            dv_timer = setTimeout(getMsg, alert_time*1000);
            window.onresize = resizeDiv;
            window.onscroll = resizeDiv;
        }
        return true;
    }
    


function getMsg()
{
	try{ 
		divTop = parseInt(document.getElementById("popMsg").style.top, 10);
		divLeft = parseInt(document.getElementById("popMsg").style.left, 10);
		docWidth = document.documentElement.clientWidth;
		docHeight = document.documentElement.clientHeight;
		document.getElementById("popMsg").style.top = parseInt(document.documentElement.scrollTop, 10) + docHeight + 10 + 'px';// divHeight

		document.getElementById("popMsg").style.left = parseInt(document.documentElement.scrollLeft, 10) + docWidth - divWidth + 'px';
		document.getElementById("popMsg").style.visibility='visible';
		document.getElementById("popMsg").style.display="block";
                
		objTimer = window.setInterval(moveDiv, 10);
	} catch(e) {
	}
}

/**
 * 用于设置判断信息框停留时间, 以及窗口大小或位置改变时信息框的位置设置
 */
function resizeDiv()
{
	try{ // 此代码仅当在窗口变化时可起作用, 而不使信息框消失等...
		docWidth = document.documentElement.clientWidth;
		docHeight = document.documentElement.clientHeight;
		document.getElementById("popMsg").style.top = docHeight - divHeight + parseInt(document.documentElement.scrollTop, 10) + 'px';
               
		document.getElementById("popMsg").style.left = docWidth - divWidth + parseInt(document.body.scrollLeft, 10) + 'px';
	} catch(e) {
	}
}

/**
 * 控制窗口渐渐上升显示
 */
function moveDiv()
{
	h_i++;
	try {
		if(h_i > divHeight+10) {
			window.clearInterval(objTimer);
		}
		divTop = parseInt(document.getElementById("popMsg").style.top, 10);
		document.getElementById("popMsg").style.top = divTop - 1 + 'px';
	} catch (e){
	}
}

/**
 * 关闭信息框
 */
function closeDiv()
{
	document.getElementById("popMsg").style.display = 'none';
	if (objTimer) {
		window.clearInterval(objTimer);
	}
	if (s_t_timer)
		window.clearInterval(s_t_timer);
}
//设为首页**收藏本站
function setHomePage(obj){
    var vDomainName="http://www.fclub.cn";
    try{//IE
        obj.style.behavior="url(#default#homepage)";
        obj.setHomePage(vDomainName);
    }catch(e){//other
        if(window.netscape) {//ff
            try {
                    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); 
            } 
            catch (e) { 
		           return false;
                    //alert("此操作被浏览器拒绝！请在浏览器地址栏输入“about:config”并回车然后将[signed.applets.codebase_principal_support]设置为'true'"); 
            }
            var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
            prefs.setCharPref('browser.startup.homepage',vDomainName);
         }
    }
    if(window.netscape)alert("ff");
}
function addFavorite(){
    var vDomainName="http://www.fclub.cn/?utm_campaign=sc";
    var description="fclub 聚尚网-品牌折扣第e站";
    try{//IE
        window.external.AddFavorite(vDomainName,description);
    }catch(e){//FF
        window.sidebar.addPanel(description,vDomainName,"");
    }
}
