
// Provide a default path to dwr.engine
if (dwr == null) var dwr = {};
if (dwr.engine == null) dwr.engine = {};
if (DWREngine == null) var DWREngine = dwr.engine;

if (SixtiethAnniversaryBean == null) var SixtiethAnniversaryBean = {};
SixtiethAnniversaryBean._path = '/activities/dwr';

SixtiethAnniversaryBean.isBlogSubmitted = function(blogUrl, callback){
	dwr.engine._execute(SixtiethAnniversaryBean._path, 'SixtiethAnniversaryBean', 'isBlogSubmitted',blogUrl, false, callback);
}

function hide(id){
	$(id).style.display='none';
}

function show(id){
	$(id).style.display='';
}

function showNext(p,n){
	hide(p);
	show(n)
}

//var preClickedElemId = "switchPanel_1";
function switchPanel(id){
	
//	var splitStr = id.split("_");
//	var sid = parseInt(splitStr[1]);
	
	var toUrl = "gq60years.do?action=index";
    var queryStr ="&numA="+id+"&orderField=checkTime&p=1";
    toUrl+=queryStr;
    
	window.location=toUrl;
}

//浮层窗口管理器
jsWindowManager = (jsWindowManager == undefined) ? new NetEase.JSWindowManager() : jsWindowManager;
var contributionWindow;

function showContributionWindow(id){
	
	$("dis_background").style.display="block";
	
	var windowOption = {
		notKeepPos : true,
		noUD : true,
		title : '活动投稿专区',
		onTop : false,
		needCover : false,
		allowScroll : false,
		opacity : 1,
		hasSystemBar: false,
		width : 635,
		panelClassName: 'content g_act_1',
		allowDrag: true
	};
	if(contributionWindow==null) contributionWindow = jsWindowManager.createWindow("活动投稿专区",windowOption);
	var data = {"userName":currentUser.userName};
	contributionWindow.panel.innerHTML =  TrimPath.parseTemplate(contributionWindowHTML).process(data);
	
	contributionWindow.showWindow();

	fillSelect("province", provinceArray);
	firstSelect("city","${city?default('')}");
    firstSelect("contributionType",id);

}
var  actCloseAlertWindow =null;

function showActCloseAlertWindow(id){

	if(actCloseAlertWindow==null) actCloseAlertWindow = jsWindowManager.createWindow("$_actCloseAlertWindowId",{
							className:'content g_act_2',width: 380, height:160, 
							title:'活动已结束',allowDrag:false,notKeepPos:true
						});
	var s = [];
		s.push('<div>');
		s.push('<p>本活动已结束，感谢您的关注和支持。</p>');		
		s.push('<p>更多精彩活动<a href="http://huodong.163.com/?fromblogmainservices&091010bx21" target="_blank" onclick="closeBox(4)">正在进行>></a></p>');
		s.push('</div>');
		
		this.actCloseAlertWindow.panel.innerHTML = s.join("");
		this.actCloseAlertWindow.showWindow();
}

function closeContributionWindow(){
	contributionWindow.hiddenWindow();
	$("dis_background").style.display="none";
	return false;
}

var contributionOkWindow;

function showContributionOkWindow(){
	
	var windowOption = {
		notKeepPos : true,
		noUD : true,
		title : '活动投稿专区',
		onTop : false,
		needCover : true,
		allowScroll : false,
		opacity : 0,
//		hasSystemBar: false,
		width : 400,
		height:180,
		panelClassName: 'content g_act_2'
	};
	if(contributionOkWindow==null) contributionOkWindow = jsWindowManager.createWindow("活动投稿专区",windowOption);
	var data = {"userName":currentUser.userName};
//	contributionOkWindow.panel.innerHTML =  $contributionOkWindowHTML;
	contributionOkWindow.panel.innerHTML =  TrimPath.parseTemplate($contributionOkWindowHTML).process(data);	      
	contributionOkWindow.showWindow();
}

var contributionFailedWindow;

function showContributionFailedWindow(){
	
	var windowOption = {
		notKeepPos : true,
		noUD : true,
		title : '活动投稿专区',
		onTop : false,
		needCover : true,
		allowScroll : false,
		opacity : 0,
//		hasSystemBar: false,
		width : 400,
		height:180,
		panelClassName: 'content g_act_2'
	};
	if(contributionFailedWindow==null) contributionFailedWindow = jsWindowManager.createWindow("活动投稿专区",windowOption);
	var data = {"userName":currentUser.userName};
//	contributionFailedWindow.panel.innerHTML =  $contributionFailedWindowHTML;
	contributionFailedWindow.panel.innerHTML =  TrimPath.parseTemplate($contributionFailedWindowHTML).process(data);	      
	contributionFailedWindow.showWindow();
}

function closeBox(id){
	switch(id){
		case 1:
		closeContributionWindow();
		break;
		case 2:
		contributionOkWindow.hiddenWindow();
		break;
		case 3:
		contributionFailedWindow.hiddenWindow();
		break;
		case 4:
		actCloseAlertWindow.hiddenWindow();
		break;
    }
}

function saveContribution(){
    addItem();
}


/**
 * 在活动投稿弹出页面中调用，活动用户投稿的一些数据,返回item，如不成功返回null
 */
function getItem(){
	
	var item ={
		"userId":currentUser.userId,
		"userName":currentUser.userName,
		"nickName":currentUser.nickName,//昵称
		"numA":$("contributionType").value, // 参赛命题id
		"descM":getTrimValue("blogUrl"), // 博客Url
		"imageUrl":getTrimValue("imageUrl"),//和你的故事相关的图片
		"smallUrl":getTrimValue("smallUrl"),
		"mediumUrl":getTrimValue("mediumUrl"),//参赛x图片
		"squareUrl":getTrimValue("squareUrl"), 
		"originWidth":getTrimValue("originWidth"),//参赛x图片
		"originHeight":getTrimValue("originHeight"),//参赛x图片
		"descF":getTrimValue("mediumWidth"),//参赛x图片
		"descG":getTrimValue("mediumHeight"),//参赛x图片
		"descN":getTrimValue("blogSummary"),//日志摘要
		"age":getTrimValue("userAge"),//年龄
		"occupation":getTrimValue("profession"),//职业
		"province":getTrimValue("province"),//省份
		"city":getTrimValue("city")//城市
		
	};

	if(item.imageUrl==""){
		dwrInfo("请上传参赛照片");
		return;
	}
	if(item.descM == ""){
		dwrInfo("请填写文章链接地址");
//		fadeTipWarn("blog_submitinfo","请填写文章链接地址",10000);
		return;
	}
	if(!checkBlogUrl(item.descM)){
		return;
	}
	if(!isValidInput2(item.descN,"日志摘要",30,1000)) return;
	if(!validateUtils.isNumberic(item.age) || !isValidInput2(item.age,"年龄",1,2)) {
		dwrInfo("请填写正确的年龄！");
		return;
	}
//	if(!isValidInput(item.occupation,"职业",1,100)) return;
//	if(!isValidInput(item.province,"地区",1,50)) return;
//	if(!isValidInput(item.city,"城市",1,50)) return;
    
//    dwrInfo(item.occupation);
//    return;
    if(item.occupation == "" || item.occupation == "请选择"){
    	dwrInfo("请选择一个职业！");
		return;
    }
    if(item.province == "" || item.province == "未设置"){
    	dwrInfo("请选择一个区域！");
		return;
    }
	return item;
}

function checkBlogUrl(blogUrl){
	if(blogUrl.indexOf("http://")<0){
		dwrInfo("请填写正确的文章链接地址，以 http:// 开头。");
//		fadeTipWarn("blog_submitinfo","请填写正确的文章链接地址，以 http:// 开头。",10000);
		return false;
	}
	if(blogUrl.indexOf("blog.163.com")<0){
		dwrInfo("请填写网易博客的文章链接地址。");
//		fadeTipWarn("blog_submitinfo","请填写网易博客的文章链接地址。",10000);
		return false;
	}
	if(blogUrl.indexOf(currentUser.userName)<0){
		dwrInfo("请填写您登陆账号的网易博客文章链接地址。");
//		fadeTipWarn("blog_submitinfo","请填写您登陆账号的网易博客文章链接地址。",10000);
		return false;
	}
	if(blogUrl.indexOf("/blog/static/") < 0){
		dwrInfo("请填写正确的网易博客文章链接地址，具体到你要提交的文章链接，地址中应包含 /blog/static/");
//		fadeTipWarn("blog_submitinfo","请填写正确的网易博客文章链接地址，具体到你要提交的文章链接，地址中应包含 /blog/static/",10000);
		return false;
	}
	return true;
}

function fadeTipWarn(id, content, durationTime){
	if($(id)){
		Element.removeClassName(id,'icn-ok');
		Element.addClassName(id,'icn-warn');
	}
	fadeTipInfo(id,content,durationTime);
}

/**
 * 在id指定的元素上显示提示内容content，持续时间durationTime，然后淡去
 * 
 * @param {}
 *            id
 * @param {}
 *            content
 * @param {}
 *            durationTime
 */
function fadeTipInfo(id, content, durationTime) {
	if ($(id)) {
		$(id).innerHTML = content;
		$(id).style.display = 'block';
		$(id).opacity = 5000;
		if (!$(id).timerId) {
			$(id).timerId = window.setInterval(function() {
						fadeInfo(id);
					}, durationTime);
		}
	}
}

$addItem_processing = false;

/**
 * 活动投稿函数
 */
function addItem(){
	
	if($addItem_processing){
		dwrInfo("正在提交...请稍候");
		return;
	}
	var item = getItem();
	if(item!=null){
		$addItem_processing = true;
//		dwrInfo(item.descM);
        
//		SixtiethAnniversaryBean.isBlogSubmitted(item.descM, function(data){isBlogSubmittedCallBack(data, item)});
//		SixtiethAnniversaryBean.isBlogSubmitted(item.descM, isBlogSubmittedCallBack);
        SixtiethAnniversaryBean.addPhotoActivitiesItem(getItem(),addItemCallback);
	}
}

function isBlogSubmittedCallBack(data){
//	$addItem_processing = false;
//    alert("正在检查...请稍候");
	if(data == false){
//		dwrInfo("您可以提交...");
//        alert(getItem());
		SixtiethAnniversaryBean.addPhotoActivitiesItem(getItem(),addItemCallback);
	}
	else{
		showContributionFailedWindow();
//		closeContributionWindow();
	}
}

/**
 * 报名的回调函数
 * @param {} data
 */
function addItemCallback(returnData){
	$addItem_processing = false;
	if(returnData > 0){
		//投稿成功
		closeContributionWindow();
		showContributionOkWindow();
		
	} else if (returnData == -1) {
		dwrInfo("照片地址不正确！");
//		effectUtils.fadeTipInfo('submitInfo',"照片地址不正确！",10);
	} else if (returnData == -2) {
//		effectUtils.fadeTipInfo('submitInfo',"服务器操作失败！",10);
        dwrInfo("服务器操作失败！");
	} else if (returnData == -3) {
//		effectUtils.fadeTipInfo('submitInfo',"验证码不正确！",10);
        dwrInfo("验证码不正确！");
	} else if (returnData == -5) {
//		effectUtils.fadeTipInfo('submitInfo',"你提交的照片不属于你的博客！",10);
        dwrInfo("你提交的照片不属于你的博客！");
	} 
	else if (returnData == -8) {
//		effectUtils.fadeTipInfo('submitInfo',"你已报名参加了本次活动，感谢你对本次活动的关注和支持。",5);
        dwrInfo("你已报名参加了本次活动，感谢你对本次活动的关注和支持。");
	}else if (returnData == -9) {
//		effectUtils.fadeTipInfo('submitInfo',"含有不合法的关键字！",5);
        dwrInfo("含有不合法的关键字！");
	}else if (returnData == -21) {
//		effectUtils.fadeTipInfo('submitInfo',"你填写的博客链接地址不正确！",5);
        dwrInfo("你填写的博客链接地址不正确！");
	}else if (returnData == -22) {
//		effectUtils.fadeTipInfo(根据你填写的博客地址，取不到博客文章照片地址不正确！");
        dwrInfo("根据你填写的博客地址，取不到博客文章地址！（地址后缀请不要加edit/）");
	}else if (returnData == -23) {
//		effectUtils.fadeTipInfo('submitInfo',"博客文章没有提交成功！",5);
        dwrInfo("博客文章没有提交成功！");
	}else if (returnData == -24) {
//		effectUtils.fadeTipInfo('submitInfo',"你提交的博客日志地址不属于你自己的博客！",5);
        dwrInfo("你提交的博客日志地址不属于你自己的博客！");
	}else if (returnData == -25) {
		//重复投稿
		closeContributionWindow();
		showContributionFailedWindow();
	}else if (returnData == -30) {
//		effectUtils.fadeTipInfo('submitInfo',"请确认游戏帐号，游戏昵称,ID与服务器是否对应并正确",5);
        dwrInfo("请确认游戏帐号，游戏昵称,ID与服务器是否对应并正确！");
	}
}

//上传照片
function openNewPhotoInterface() {
	
	document.domain = "163.com";
	window.PhotoInterfaceCallback = newphotoInterfaceCallback;
	var dialog = window
			.open(
					"http://"
							+ DomainMap.getParentDomain(currentUser.userName)
							+ "/photoInterface.do?target=player&uploadLimit=1&selectLimit=1&tabIdx=1",
					"_addBlogPic",
					"resizable=no,scrollbars=yes,status=yes, width=780px, height=500px, left="
							+ (window.screen.width - 780) / 2 + " top="
							+ (window.screen.height - 500) / 2);
}
/**
 * 照片上传窗口中调用的回调函数
 */
var photo = {};
function newphotoInterfaceCallback(photoList) {
	if (photoList && photoList.length > 0) {
		
		Object.extend(photo, photoList[0]);
		// 在页面上预览图片
		$("photoSrc").src= photo.smallUrl;
		$("photoSrc").onload=" fcbbs.Utils.autoResizeImageStrict(this,130,99)";

		$("uploadImgDiv3").style.display = "none";
		$("uploadImgDiv").style.display = "none";
		$("uploadImgDiv2").style.display = "block";
		
//		SixtiethAnniversaryBean.updateFields({"imageUrl":photo.url,"squareUrl":photo.squareUrl,"smallImageUrl":photo.smallUrl,"mediumUrl":photo.mediumUrl,"originWidth":photo.originWidth,"originHeight":photo.originHeight,"descF":photo.mediumWidth,"descG":photo.mediumHeight},$_itemId,postUpdatePhoto);
	}
}

function reUpLoadImg(){
	openNewPhotoInterface();
}

function okUpLoadImg(){
	$("uploadImgDiv3").style.display = "block";
	$("uploadImgDiv2").style.display = "none";
	$("uploadImgDiv").style.display = "block";
	
	$("photoSrc2").src= photo.smallUrl;
	$("photoSrc2").onload=" fcbbs.Utils.autoResizeImageStrict(this,130,99)";
	$("imageUrl").value = photo.url;
	$("smallUrl").value = photo.smallUrl;
	$("mediumUrl").value = photo.mediumUrl;
	$("squareUrl").value = photo.squareUrl;
	$("originWidth").value = photo.originWidth;
	$("originHeight").value = photo.originHeight;
	$("mediumWidth").value = photo.mediumWidth;
	$("mediumHeight").value = photo.mediumHeight;
}

function isValidInput2(textValue,textLabel,minLen,maxLen){if(minLen>0&&textValue==""){dwrInfo(textLabel+"必填","error");return false;}
if(textValue.len()>maxLen){dwrInfo(textLabel+"不能超过"+maxLen+"个字","error");return false;}	
if (textValue.length<minLen){dwrInfo(textLabel+"必须超过"+minLen+"个字","error");	return false;}
return true;}


 function copyToClipboard (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"之后重试。');
						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);
				}
				return true;
}

function copyprourl(intro, link){
	var txt = intro+" "+link;
	if(copyToClipboard(txt)){
		
		alert("复制活动地址成功！你可以直接粘贴到MSN、POPO、QQ上，邀请你的好友一起来参加！");
		
		
	}
}

function checkText(type,id){
	var text = $(id).value;
	if(type==0){
		if(text=="30字以上")
			$(id).value = "";
	}
	if(type==1){
		if(text==""){
			if(id=="blogSummary")
				$(id).value = "30字以上";
		
		}
	}
}

function lenLimit(id, len){
	var content = $(id).value;
	if(content.len()<len){
		if(id=="blogSummary")
			dwrInfo("日志摘要过少，请控制在30字以上。");
		
	}
}

String.prototype.len=function(){ 
return this.replace(/[^\x00-\xff]/g,"**").length; 
} 

function imgFix() { 
  //定义要限制的图片宽高,这个宽高要同style里面定义的相同，小于限定高宽的图片不操作 
  var widthRestriction = 106; 
  var heightRestriction = 106; 
  var allElements = document.getElementsByTagName('*')   
  for (var i = 0; i < allElements.length; i++) 
  { 
    if (allElements[i].className.indexOf('img106x106') >= 0) 
        { 
      var imgElements = allElements[i].getElementsByTagName('img'); 
      for (var j=0; j < imgElements.length; j++) 
          { 
        if ( imgElements[j].width > widthRestriction || imgElements[j].height > heightRestriction ) 
                { 
          if ( imgElements[j].width > imgElements[j].height) 
                  { 
            imgElements[j].height = heightRestriction; //imgElements[j].height*(widthRestriction/imgElements[j].width); 
            imgElements[j].width = widthRestriction; 
          } else 
                  { 
            imgElements[j].width = widthRestriction; //imgElements[j].width*(heightRestriction/imgElements[j].height); 
            imgElements[j].height = heightRestriction; 
          } 
        } 
                if ( imgElements[j].height < heightRestriction ) 
                { 
                  imgElements[j].style.paddingTop = ( heightRestriction -imgElements[j].height ) /2 + "px"; 
                } 
      } /*for j*/ 
    } 
  }/*for i*/ 
} 
//window.onload = imgFix;

function imgFixOnce(_e, widthRestriction, heightRestriction) { 
  //定义要限制的图片宽高,这个宽高要同style里面定义的相同，小于限定高宽的图片不操作 
//  var widthRestriction = 106; 
//  var heightRestriction = 106; 
  
  var _w = _e.style.width;
  var _h = _e.style.height; 
  if ( _w > widthRestriction || _h > heightRestriction ) 
                { 
          if ( _w > _h) 
                  { 
            _e.style.height = heightRestriction; //imgElements[j].height*(widthRestriction/imgElements[j].width); 
            _e.style.width = widthRestriction; 
          } else 
                  { 
            _e.style.width = widthRestriction; //imgElements[j].width*(heightRestriction/imgElements[j].height); 
            _e.style.height = heightRestriction; 
          } 
        } 
//                if ( _h < heightRestriction ) 
//                { 
//                  _e.style.paddingTop = ( heightRestriction -_h ) /2 + "px"; 
//                }  
} 
