document.domain = 'alibaba.com';
var favoriteData = {}
var createFavWin = function (noIframe) {
    // set winWrap width and height
    var iWidth = 468,
        iHeight = 165;
	
	var elWinWrap;
	
	if(!get('winFavWrap')){
		elWinWrap = document.createElement('div');
		
		var wrapHTML = '';
		wrapHTML += '<div class="winFav" id="winFav">';
		wrapHTML += '<h5 id="titleAddFav">Add product to Favorites</h5>';
		wrapHTML += '<a href="javascript:void(0);" id="iconCloseWin" class="iconCloseWin">close</a>';
		if (!noIframe) {
			wrapHTML += '<iframe id="frmRequestAddFav" width="368" class="frmRequestAddFav" src="" scrolling="no" frameborder="0"></iframe>';
		}
		wrapHTML += '</div>';
		wrapHTML += '<div class="shadow"></div>';

		elWinWrap.id = 'winFavWrap';
		elWinWrap.className = 'winFavWrap';
		elWinWrap.innerHTML = wrapHTML;
		document.body.appendChild(elWinWrap);
	}else{
		elWinWrap = get('winFavWrap');
		get('pageShadow').style.display = 'block' ;
	}
	
	//¶¨Î»
	elWinWrap.style.width = iWidth + 'px';
	if (AE.bom.isIE6) {
		elWinWrap.style.top = (document.documentElement.clientHeight - iHeight) / 2 + document.documentElement.scrollTop + 'px';
	} else {
		elWinWrap.style.top = (document.documentElement.clientHeight - iHeight) / 2 + 'px';
	}
	
	//shadow
	if (!get('pageShadow')){
		var elShadow = document.createElement('div') ;
		elShadow.id = 'pageShadow' ;
		elShadow.style.cssText = 'position:absolute;top:0;left:0;width: 100%;z-index:999998;background-color: #000;filter:alpha(opacity=20);opacity:0.1 ;' ;
		elShadow.style.height = document.documentElement.scrollHeight+'px' ;

		document.body.appendChild(elShadow) ;
	}else {
		get('pageShadow').style.display = 'block' ;
		get('pageShadow').style.visibility = 'visible' ;
		get('pageShadow').style.height = document.documentElement.scrollHeight+'px' ;
	}

    //
    YUE.on(['iconCloseWin','btnClose-OperationFailed'], 'click', function () {
        clearWin();
    });

};


var clearWin = function () {
    if (workingLink !== null) {
        YUD.removeClass(workingLink, 'show');
        workingLink.parentNode.style.visibility = 'hidden';
        if (isGallery) {
            workingLink.parentNode.parentNode.style.background = '';
        }
    }
    try {
		get('winFavWrap').style.display = 'none';
		get('pageShadow').style.display = 'none';
        //document.body.removeChild(get('winFavWrap'));
		//document.body.removeChild(get('pageShadow'));
		//get('pageShadow').style.visibility = 'hidden' ;
		//get('pageShadow').style.height = 'auto' ;
    } catch (e) {}
}

var closeWinEsc = function () {
    document.onkeyup = function (e) {
        var e = window.event || e;
        if (e.keyCode == 27) {
            clearWin();
            document.onkeyup = null;
        }
    };
};



var workingLink = null;
var isGallery = false;
var urlRule;


YUE.onDOMReady(function () {
    try {
        urlRule = get('favoriteUrlRule').value;
    }
    catch (e) { }

    //clickshow
    var clickkShowConfig = {
        targetId: "menuRight",
        contentId: "addMenuContent",
        needMask: true,
        excursion: [-151, -1]
    };
    var clickkShowInstance = new AE.widget.clickShow();
    clickkShowInstance.init(clickkShowConfig);

    YUE.on(['addCompany', 'addProduct'], 'click', function () {
        toAddFavorite(this);
        clickkShowInstance.hiddenDirectly(null, true)
    });

    YUE.on(['menuText', 'linkAddCompany'], 'click', function () {
        toAddFavorite(this);
    });

    var toAddFavorite = function (target) {
        var objectType = target.getAttribute('objecttype');
        var objectId = target.getAttribute('objectid');
        addFavorite(objectType, urlRule, objectId);
    }

    var addFavorite = function (objectType, urlRule, objectId) {
        createFavWin();
        var sUrl = get('favoriteServer').value + '/favorite/frmAddFav.htm';
        get('titleAddFav').innerHTML = 'Please login';
        get('winFavWrap').style.display = 'block';
        var ts = +new Date();
		
		if(typeof(aisnSite) == 'undefined' || aisnSite == 'intl') {
			get('frmRequestAddFav').src = sUrl + '?action=AddFavoriteAction&event_submit_do_add_favorite=anything&objectType=' + objectType + '&objectId=' + objectId + '&urlRule=' + urlRule + '&ts=' + ts;
		} else {
			get('frmRequestAddFav').src = sUrl + '?action=AddFavoriteAction&event_submit_do_add_favorite=anything&objectType=' + objectType + '&objectId=' + objectId + '&urlRule=' + urlRule + '&ts=' + ts +'&aisnSite=' + aisnSite;
		}
    }

    var atfButton = YUD.getElementsByClassName('add-to-favorite', 'div');

    YUE.on(atfButton, 'click', function (e) {
    	if (YUD.getElementsByClassName('success', 'span', this).length > 0) {
    		return;
    	};
        if (workingLink !== null) {
            YUD.removeClass(workingLink, 'show');
            workingLink.parentNode.style.visibility = 'hidden';
        }

        workingLink = YUD.getFirstChild(this);
        YUD.addClass(workingLink, 'show');

        var userId     = this.getAttribute('userid');
        var objectType = this.getAttribute('objecttype');
        var objectId   = this.getAttribute('objectid');
        
        addFavoriteNoWin(userId, objectType, objectId);
    });

    var gtfButton = YUD.getElementsByClassName('gallery-to-favorite', 'div');
    
    if (gtfButton.length > 0) {
    	isGallery = true;
    }

    YUE.on(gtfButton, 'click', function (e) {
    	if (YUD.hasClass(this, 'success')) {
    		return;
    	}
        if (workingLink !== null) {
            YUD.removeClass(workingLink, 'show');
            workingLink.parentNode.style.visibility = 'hidden';
            workingLink.parentNode.parentNode.style.background = '';
        }
        
        workingLink = this;
        YUD.addClass(workingLink, 'show');
        
        var userId     = this.getAttribute('userid');
        var objectType = this.getAttribute('objecttype');
        var objectId   = this.getAttribute('objectid');
        
        addFavoriteNoWin(userId, objectType, objectId);
	});
});

var createWherecan = function () {
    var divWhereCan = document.createElement('div');
    divWhereCan.className = 'bubbleBox';
    divWhereCan.id = 'whereCan';
    var divWinBubble = document.createElement('div');
    divWinBubble.className = 'winBubble';
    var divWinBg = document.createElement('div');
    divWinBg.className = 'winBg';
    var title = document.createElement('h4');
    title.innerHTML = 'Where can you look at your favorites?';
    var iconCloseWin = document.createElement('a');
    iconCloseWin.id = 'iconCloseWhereCan';
    iconCloseWin.className = 'iconCloseWin';
    iconCloseWin.innerHTML = 'close';
    var bubbleInfo = document.createElement('p');
    bubbleInfo.className = 'bubbleInfo';
    bubbleInfo.innerHTML = 'You can navigate this site to any page location to find ways to enter';
    var spanWhereCan = document.createElement('span');
    spanWhereCan.id = 'spanWhereCan';
    spanWhereCan.innerHTML = 'Got it, thank you!';
    var winPoint = document.createElement('div');
    winPoint.className = 'winPoint';

    divWinBg.appendChild(title);
    divWinBg.appendChild(iconCloseWin);
    divWinBg.appendChild(bubbleInfo);
    divWinBg.appendChild(spanWhereCan);

    divWinBubble.appendChild(divWinBg);

    divWhereCan.appendChild(divWinBubble);
    divWhereCan.appendChild(winPoint);
    document.body.appendChild(divWhereCan);
}

var setWinWherecan = function () {
    YUD.setStyle('whereCan', 'display', 'block');
    var x = YUD.getX('currentHelp') - 110;
    var y = YUD.getY('currentHelp') + 15;
    YUD.setXY('whereCan', [x, y]);
}



var addFavoriteNoWin = function (userId, objectType, objectId) {
	favoriteData.userId = userId;
	favoriteData.objectType = objectType;
	favoriteData.objectId = objectId;
	popUpXman();
}

function popUpXman() {
	var loginFlag = AE.bom.getCookie('ali_non_s_temp'); 
	if( loginFlag.indexOf('is_sign=y')  == -1){
		var xmanjsUrl = "https://login.alibaba.com/xman/xman.js?pd=alibaba&display=p&style=b&modal=n&join=a&tab=l&back=g&delay=true&title=a&link=a&login=a&lbutton=b&jbutton=b&callback=addFavoriteCallback";
		if (!AE.xman_join_login) {
			YAHOO.util.Get.script(xmanjsUrl, {onSuccess: 
				function(){
					AE.xman_join_login.boxPopup();
				}
			});
		} else {
			AE.xman_join_login.boxPopup();
		}
	} else {
		addFavoriteCallback();
	}
}

function addFavoriteCallback() {
	var sUrl = get('favoriteServer').value + '/favorite/ajaxAddFavorite.htm';
	var postData = 'action=AddFavoriteAction&event_submit_do_add_favorite=anything&objectType=' + favoriteData.objectType + '&objectId=' + favoriteData.objectId + '&urlRule=' + urlRule + '&ts=' + new Date();
	var callBack = {}

	YAHOO.util.Connect.setForm(document.getElementById('favoriteForm'), true);
	YAHOO.util.Connect.asyncRequest('POST', sUrl + '?' + postData, callBack, postData);
	
	AE.xman_join_login.boxClose();
	if (workingLink !== null && favoriteData.userId != '') {
		addAjaxLoading(workingLink);
	}
}
	
var addFavNoWinSuccess = function (objNode) {
    var favoriteUrl = get('favoriteServer').value + '/favorite/favoriteHome.htm';
    YUD.removeClass(objNode, 'working');
    YUD.addClass(objNode, 'success');
    objNode.innerHTML = 'Added to <a href="../Qingdao Luckall Hardware Co_, Ltd_ - Rigging, hardware, chain.files/' + favoriteUrl + '" style="line-height:20px" target="_blank">Favorites</a>';

    if (isGallery) {
    	setTimeout(function () {
    		YUD.removeClass(objNode, 'show');
            objNode.parentNode.style.visibility = 'hidden';
            objNode.parentNode.parentNode.style.background = '';
	    }, 1500);
    }
}
var addFavNoWinFail = function (objNode) {
    objNode.className = 'atf-button';
}
var addAjaxLoading = function (objNode) {
	YUD.addClass(objNode, 'working');
}

var showWarnWin = function (type,text) {
    createFavWin('noIframe');
	
    get('titleAddFav').innerHTML = 'System Error';
    get('winFavWrap').style.display = 'block';
	get('winFavWrap').style.width = '460px';
	get('winFavWrap').style.marginLeft = '-230px';
	
    var contentBox = document.createElement('div');
    contentBox.className = 'contentBox'
    var errorInfo = document.createElement('div');
    errorInfo.className = 'errorInfo doWarn';
    errorInfo.id = 'errorInfo';
    errorInfo.innerHTML = '<i class="' + type + '">?</i>' + text;
    var btnDiv = document.createElement('div');
    btnDiv.className = 'btnSysError';
    btnDiv.innerHTML = '<input type="button" id="btnClose-OperationFailed" class="btnCommon btnWarn" value="OK" />';

    contentBox.appendChild(errorInfo);
    contentBox.appendChild(btnDiv);

    get('winFav').appendChild(contentBox);
}

var favorCallback = function (resultObj) {
    if (resultObj.result == '' || resultObj.result == 'FavoriteExsit') {
        if (workingLink !== null) {
            addFavNoWinSuccess(workingLink);
            workingLink = null;
        }
        if (get('winFavWrap')) {
            clearWin();
        }
    }
    else if (resultObj.result == 'unLogin') {
		
        createFavWin();
        get('titleAddFav').innerHTML = 'Please login';
        get('winFavWrap').style.display = 'block';
        get('frmRequestAddFav').src = resultObj.location + '&ts=' + new Date();
    }
	else if (resultObj.result == 'FavoriteCountLimit') {
		if (workingLink !== null) {
            YUD.removeClass(workingLink, 'working');
            YUD.removeClass(workingLink, 'show');
            workingLink = null;
        }
        if (get('winFavWrap')) {
            clearWin();
        }
		showWarnWin('warn','Supports up to 1000 items added.');
	}
    else {
        if (workingLink !== null) {
            YUD.removeClass(workingLink, 'working');
            YUD.removeClass(workingLink, 'show');
            workingLink = null;
        }
        if (get('winFavWrap')) {
            clearWin();
        }
		showWarnWin('sysError','Due to errors in the system, this item cannot to added.');
    }
}

YUE.on(window, 'resize', function(){
	if (get('whereCan')) {
		setTimeout(setBubble,1000);
		//setBubble();
	}
});

//bubble

var createBubble = function(closeBubbleType,CsrfTokenName,CsrfTokenValue,jsonResultUrl){
	var getMyFavorite = YUD.getElementsByClassName('help','li',get('mainNavig'))[0];
	if (getMyFavorite == undefined) {
		return false;
	}
	var data = document.createElement('input');
	data.id = 'favoriteBubbleData';
	data.type = "hidden";
	data.setAttribute('closeBubbleType',closeBubbleType);
	data.setAttribute('CsrfTokenName',CsrfTokenName);
	data.setAttribute('CsrfTokenValue',CsrfTokenValue);
	data.setAttribute('jsonResultUrl',jsonResultUrl);
	
	var form = document.createElement('form');
	form.id = 'favBubbleForm';
	form.style.disply = 'none';
	
	var divWhereCan = document.createElement('div');
	divWhereCan.className = 'bubbleBox';
	divWhereCan.id = 'whereCan';
	var divWinBubble = document.createElement('div');
	divWinBubble.className = 'winBubble';
	var divWinBg = document.createElement('div');
	divWinBg.className = 'winBg';
	var title = document.createElement('h4');
	title.innerHTML = 'Where can you find My Favorites?';
	var iconCloseWin = document.createElement('a');
	iconCloseWin.href = "javascript:void(0);";
	iconCloseWin.id = 'iconCloseWhereCan';
	iconCloseWin.className = 'iconCloseWin';
	iconCloseWin.innerHTML = 'close';
	var bubbleInfo = document.createElement('p');
	bubbleInfo.className = 'bubbleInfo';
	bubbleInfo.innerHTML = "The navigation tab to 'My Favorites' can be found at the top right corner of every Alibaba.com page. ";
	var winPoint = document.createElement('div');
	winPoint.className = 'winPoint';
	
	document.body.appendChild(divWhereCan);
	
	divWhereCan.appendChild(divWinBubble);
	divWhereCan.appendChild(winPoint);
	divWhereCan.appendChild(data);
	divWhereCan.appendChild(form);
	
	divWinBubble.appendChild(divWinBg);
	
	divWinBg.appendChild(title);
	divWinBg.appendChild(iconCloseWin);
	divWinBg.appendChild(bubbleInfo);
}

var setBubble = function(){
	var getMyFavorite = YUD.getElementsByClassName('help','li',get('mainNavig'))[0];
	if (getMyFavorite != undefined) {
		var x = YUD.getX(getMyFavorite) - 200;
		var y = YUD.getY(getMyFavorite) + 15;

		
		//YUD.setStyle('whereCan', 'display', 'block');
		YUD.setXY('whereCan', [x, y]);

	} else {
		return false;
	}
}
var showBubble = function() {
	YUD.setStyle('whereCan', 'display', 'block');
}

var submitForBubble = function(closeBubbleType,closeId,CsrfTokenName,CsrfTokenValue,jsonResultUrl){

	var postData = 'action=' + 'closeBubbleAction&' + closeBubbleType + '=' + closeId + '&' + CsrfTokenName + '=' + CsrfTokenValue;
	var callBack = {};
    YAHOO.util.Connect.setForm(document.getElementById('favBubbleForm'), true);

    YAHOO.util.Connect.asyncRequest('POST', jsonResultUrl + '?' + postData, callBack, postData);

}

YUE.on('iconCloseWhereCan', 'click', function(){
	var data = get('favoriteBubbleData');
	var closeBubbleType = data.getAttribute('closeBubbleType');
	var CsrfTokenName = data.getAttribute('CsrfTokenName');
	var CsrfTokenValue = data.getAttribute('CsrfTokenValue');
	var jsonResultUrl = data.getAttribute('jsonResultUrl');
	
	submitForBubble(closeBubbleType,'whereCan',CsrfTokenName,CsrfTokenValue,jsonResultUrl);
	YUD.setStyle('whereCan', 'display', 'none');
});



