var global_privacy=-1;
var global_imgsrcArray = null;
var global_lastQuery;
var selectLockOn = false;
/*
if (ws_ajax_path_prefix != ""){
	var tempLen = ws_ajax_path_prefix.split("/").length;
	tempLen = tempLen-1;
	if (tempLen > 2){
		ws_ajax_path_prefix="";
		for (var i=0;i<tempLen-2;i++) {
			ws_ajax_path_prefix += "../";	
		}
	}else{
		ws_ajax_path_prefix="";
	}
}else{
	ws_ajax_path_prefix="";
}

if (location.host.indexOf(".com")>-1){
	ws_ajax_path_prefix = "/";
}
*/
	
$(document).ready(function() {
	var ws_ajax_path_prefix = $("#thickboxContext").val();
	var ws_ajax_host  =  window.location.host;
	sitesPage.bindRadioClick();
	sitesPage.bindCheckClick();
	addEditable();
	//initialize the fist thumbnail so it's selected by default
	$.each($(".thumb").eq(0).find(".thumb_border"), function() {
		sitesPage.selectThumb($(this));
	});
	$(".clickThumb").unbind("click");
	$(".clickThumb").click(function () {
		var pageView = $(this).attr("pageView");

//		var uniqiueVisits = $(this).attr("uniqiueVisits");
//		if (uniqiueVisits == null || uniqiueVisits == "")
//			uniqiueVisits="0";
//		var visitors = $(this).attr("visitors");
//		if (visitors == null || visitors == "")
//			visitors="0";
//		var query = "antiCache="+((new Date()).getTime())+"&tid="+$(this).attr("id")+"&path="+ws_ajax_host+"&pageViews="+pageView+"&uniqiueVisits="+uniqiueVisits+"&visitors="+visitors;
        var query = "antiCache="+((new Date()).getTime())+"&tid="+$(this).attr("id")+"&path="+ws_ajax_host+"&pageViews="+pageView;
		$.getJSON(ws_ajax_path_prefix+"sac?"+query+"&callback=?",
				   function(json){
					  if (json != "") {								
									sitesPage.updateBigImage(json);
								}
				   }
				);	
	

//    var query1 = "antiCache="+((new Date()).getTime())+"&tid="+$(this).attr("id")+"&path="+ws_ajax_host;
//    alert(ws_ajax_path_prefix+"sgc?"+query1+"&callback=?");
//	$.getJSON(ws_ajax_path_prefix+"sgc?"+query1+"&callback=?",
//			   function(json){
//				  if (json != "") {			
//				  			alert("js/"+json.pageViews);					
//								$("#pageViews").html(json.pageViews);   
//							}
//			   }
//			);	
	
	});
	
	
	

	
	
	
	$(".naviBigPage a").click(function () {							
		if ( $(this).hasClass("disable") ){
			return;	
		}
		var query = "antiCache="+((new Date()).getTime())+"&"+$(this).attr("ref")+"&path="+ws_ajax_host;

		$.getJSON(ws_ajax_path_prefix+"sac?"+query+"&callback=?",
				   function(json){
					  if (json != "") {									
									sitesPage.updateBigImage(json);
									
								}
				   }
				);		
		/*
		$.ajax({url:ws_ajax_path_prefix+"sac?"+query,
                 type: 'GET',
                 dataType: 'json',
                 timeout: 10000,
                 error: function(){ 
                 },
                success:function(json){
					if (json != "") {
						sitesPage.updateBigImage(json);
						
					}
				}
		});
		*/
	
	});	
	
	
	// apply click event to all thumbnails
	// assumes images for the big image are named: big_img_#
	// assumes images for the thumbnails are named: thumb_img_#
	// assumes images for the grey thumbnail border are named: thumb_...
	// assumes images for the grey thumbnail border are named: hi_...
	$(".thumb").click(function() {
		///var update = new Array("Updated June 16, 2008", "Updated April 26, 2008", "Updated February 2, 2008", "Updated March 9, 2008");
		///var img_name = $(this).find(".thumb_image_border").attr("src");
		///$(".big_image_border").attr("src",img_name.replace(/thumb/,"big"));
		///$(".big_image_date").text(update[img_name.charAt(img_name.search(/img_/) + 4) -1]);
		
		//change the previously selected thumbnail border to grey
		$.each($.find(".thumb_selected"), function(){
			sitesPage.deselectThumb($(this));
		});
		
		//change the selected thumbnail border to blue
		$.each($(this).find(".thumb_border"), function() {
			sitesPage.selectThumb($(this));
		});
	});
	
	
	$("#hasDomain").attr("checked",true);
	$("#modifyDomain").attr("checked",true);
	
	function checkDomainLimit (){
		var domainMappingCount = $("#domainMappingCount").val();
		var domainLimitCount = $("#domainMappingCount").attr("name").replace("domainLimitCount","");
		
		var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=MessageWindow";
		if (Number(domainMappingCount) <= 0){
			messageWindow("You have reached your limit of "+domainLimitCount+" domain mappings for this account level",dialogueUrl);
			return false;
		}else{
			return true;	
		}
	}
	
	$("#domainMappingArea a").click(function (){

				$(".errorInfo").hide();
				if ($(this).hasClass("editted")){
					
					$("#iptDomainAddressEdit").val($("#domainMappingArea span").text());	
					
					$("#modifyDomain").attr("checked",true);
					
					var ws_ajax_path_prefix = $("#thickboxContext").val();
					$("#modDomainDetail").attr("href","http://free-webpage.websketch.com/Domains/GoDaddy");
					var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=DomainEdittingWindow";								
					tb_initForce(dialogueUrl);
				}else{
																  
					if (checkDomainLimit()){							  
					
						$("#iptDomainAddress").val("");				
						$("#hasDomain").attr("checked",true);
						var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=DomainWindow";								
						tb_initForce(dialogueUrl);
						$("#domainStep1").show();								
						$("#domainStep2").hide();
						$("#btnDomainAdd").hide();
						$("#btnDomainNext").show();	
					}
				}
											
	});
	

	
	//document.getElementById("PageTitleSelect").innerHTML = document.getElementById("PageTitleSelectPool").innerHTML;
	//$("#PageTitleSelectPool").remove();
	
	$("#PageTitleSelectPool li").each(function (){
				$("#PageTitleSelect").append($(this));								
	});

	$('#PageTitleSelect').each(function (){
		var srcId = $(this).attr("id")+"-opener";				   
		var pos  = Util.getElementPos(srcId);
			//$(this).css({left:pos.x-($("#EditSelect").width()-$("#"+srcId).width()),top:pos.y+$("#"+srcId).height()});
	
		var limitTop = $("#footerZoneSites").offset().top;
		if(  (pos.y + $(this).height()) > limitTop ){
			$(this).css({left:pos.x-$(this).width(),top:pos.y-$(this).height()});
			
		}else{
			$(this).css({left:pos.x,top:pos.y});	
			
		}
		
				
						   
	});
	
	$("#SortSelect .ws_option").click(function () {
		
		var sortType = $(this).attr("id");
		sortType = sortType.replace("sort_","");
		var sortOrder = $("#sortTypeValue").val();
		
		GallerySort(sortType,sortOrder);
		$("#sortBoxValue").val(sortType);			
		$(".selectbox").hide();
		$("#choosedSortCaption").html(" "+$(this).text()+" ");		
	});	
	
	$("#PageTitleSelect a").click(function (){
		$(".selectbox").hide();									
											
		var query = "antiCache="+((new Date()).getTime())+"&"+$(this).attr("rel")+"&path="+ws_ajax_host;
	
	$.getJSON(ws_ajax_path_prefix+"sac?"+query+"&callback=?",
			   function(json){
				  if (json != "") {								
								sitesPage.updateBigImage(json);
								
							}
			   }
			);					  
	});	//end click function		
	
		
	$(".ws-opener").click(function (){	
		//$("#ws_selectBox").show();
		var target = $(this).attr("id");
		var srcId = target;
		target = target.replace("-opener","");
		
		var targetList = $("#"+target);
		var showList = true;

		if (target == "PageTitleSelect"){
			var nameListSize = $("#PageTitleSelect li").size();
			
			//if (nameListSize <=1 ){
			//	showList = false;	
			//}
			
			var pos  = Util.getElementPos("PageTitleSelect-opener");
				//$(this).css({left:pos.x-($("#EditSelect").width()-$("#"+srcId).width()),top:pos.y+$("#"+srcId).height()});
		
			var limitTop = $("#footerZoneSites").offset().top-10;
			if(  (pos.y + $("#PageTitleSelect").height()) > limitTop ){
				$("#PageTitleSelect").css({left:pos.x-$("#PageTitleSelect").width()+17,top:pos.y-$("#PageTitleSelect").height()});
				
			}else{
				$("#PageTitleSelect").css({left:pos.x-$("#PageTitleSelect").width()+17,top:pos.y+21});	
				
			}
		}
		if (showList){
			targetList.show();
			selectLockOn = true;
		}
	});
	
	$("#big_image_pageName h2").click(function (){
			sitesPage.hideSelectBox();									
												
	});
	
	$('#big_image_pageName').bind("mouseleave",function () {
		if (selectLockOn == true){
		
			sitesPage.hideSelectBox();

		}
		
	});
	
	$('#sortBox').bind("mouseleave",function () {
		if (selectLockOn == true){
		
			sitesPage.hideSelectBox();

		}
		
	});	
	
	$('.selectbox').bind("mouseenter",function () {
		$(this).show();
		
	});

	$('.selectbox').bind("mouseleave",function () {
		if (selectLockOn == true){
		
			sitesPage.hideSelectBox();
			selectLockOn = false;
		}
		
	});
		
	$(".asc_order").click(function (){	
		$("#sortTypeValue").val("asc");
		$(".desc_order").attr("id","unselectedOrder");
		$(this).attr("id","selectedAscOrder");
		GallerySort($("#sortBoxValue").val(),"asc");
	});	
	$(".desc_order").click(function (){	
		$("#sortTypeValue").val("dec");
		$(".asc_order").attr("id","unselectedOrder");
		$(this).attr("id","selectedDscOrder");		
		GallerySort($("#sortBoxValue").val(),"dec");
	});			

});

function addEditable(){
	var ws_ajax_path_prefix = $("#thickboxContext").val();
	var ws_ajax_host  =  window.location.host;
	$("#bigImageTitleMarkup .inline-edit h2").editable(ws_ajax_path_prefix+"changeTitle",{
	onblur:'submit',
	dataType:'json',
    ajaxType:'jsonp',
	charLimit:30,
	onkeyup:function (inputHandle) {	
			textLimit(inputHandle,30);
		},
    cssclass : "editableSingleLineLabel1", 
	placeholder:'( Click here to add a site title )',
	callback:function (value,settings){
		var responseStr = value.data;
		
		if (value.error != null && value.error != ""){
			if (value.data != value.targetName){
				var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=MessageWindow";
				messageWindow("You already have a site titled '"+value.targetName+"'.  Please give a unique site title for this site.",dialogueUrl);
			}
		}else{
				if (responseStr.replace(/^\s*$/g,'') =="" || responseStr=="null" || responseStr == "( Click here to add a site title )"){
					$(this).attr("class","notEditedLabel noteName");
					//value.slugName = $("#currentThumbSnoteId").text();
					responseStr = "Untitled";
					$(this).attr("name",$(this).attr("id").replace("t",""));
				}else{
					$(this).attr("class","hasBeenEditedLabel noteName");
				}
					//check if the user is premium or not
					var premiumFlag = $("#easyurl").val();
					//var domainUrl = $("#bigImageDomainMarkup p").html();					
					var domainUrl = $("#domainMappingArea span").html();
					//domainUrl = domainUrl.replace('( Click here to add a domain name )','');
					//if user is premium and he has no domain mapping for current site
					//then, update the easyurl's site title part.
					if (premiumFlag == "1"  && domainUrl == ''){
						//update the easy url link
						var easyDomain = $("#bigImageEasyUrlMarkup p").attr("name");
						easyDomain = easyDomain.replace(/\/$/,"");
						var newUrl = easyDomain + "/"+ value.slugName+"/"+$("#big_image_pageName h2").attr("name");

						 $("#bigImageEasyUrlMarkup a").attr("href",newUrl);
						 $("#bigImageEasyUrlMarkup a").html(newUrl);
						 
						// sitesPage.updateUrlAfterTitleChanged(value.slugName,$(this).attr("name"));
						sitesPage.updateBigThumbnailUrlByManual(newUrl);
						
						
					}
					//use h2@name to store slugname 
					$(this).attr("name",value.slugName);
					sitesPage.updateSiteTitle(responseStr);
		}
	}
	});


	$("#bigImageKeywordsMarkup .inline-edit p").editable(ws_ajax_path_prefix+"changeTitle",{
	onblur:'submit',
	dataType:'json',
	ajaxType:'jsonp',
	charLimit:40,
	onkeyup:function (inputHandle) {	
			textLimit(inputHandle,40);
		},	
    cssclass : "editableMultiLineLabel1",
	placeholder:'( Click here to add a keyword )',
	callback:function (value,settings){
		value = value.data;
		if (value.replace(/^\s*$/g,'') =="" || value=="null"){
			$(this).attr("class","notEditedLabel");
		}else{
			$(this).attr("class","hasBeenEditedLabel");
		}
	}
	});
	
	$("#bigImageTagsMarkup .inline-edit p").editable(ws_ajax_path_prefix+"changeTitle",{
	onblur:'submit',
	dataType:'json',
	ajaxType:'jsonp',
	onkeyup:function (inputHandle) {
			
			wordLimit(inputHandle,5," ");
			
		},	
	type:'textarea',
    cssclass : "editableMultiLineLabel1",
    rows:2,
	placeholder:'( Click here to add tags )',
	callback:function (value,settings){
		value = value.data;
		if (value.replace(/^\s*$/g,'') =="" || value=="null"){
			$(this).attr("class","notEditedLabel");
		}else{
			$(this).attr("class","hasBeenEditedLabel");
		}
	}
	});
		
	
	
	$("#bigImageDescMarkup .inline-edit p").editable(ws_ajax_path_prefix+"changeTitle",{
	onblur:'submit',
	dataType:'json',
	ajaxType:'jsonp',
	type:'textarea',
    cssclass : "editableMultiLineLabel1", 
	rows:8,
	placeholder:'( Click here to add a description )',
	callback:function (value){
		value = value.data;
		Util.log(value);
		if (value.replace(/^\s*$/g,'') =="" || value=="null"){
			$(this).attr("class","notEditedLabel");
		}else{
			$(this).attr("class","hasBeenEditedLabel");
		}
	}
	});	
	
	
	
	$("#bigImageDomainMarkup .inline-edit p").editable(ws_ajax_path_prefix+"changeTitle",{
	onblur:'submit',
	dataType:'json',
	ajaxType:'jsonp',
	charLimit:40,
	onkeyup:function (inputHandle) {	
			textLimit(inputHandle,40);
		},
    cssclass : "editableSingleLineLabel2", 
	placeholder:'( Click here to add a domain name )',
	callback:function (value,settings){
	
		var responseStr = value.data;
		
		if (value.error != null && value.error != ""){
		     
			var message=value.error;
			if(message.indexOf("domain mappings")>1)
			{
				var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=MessageWindow";
				messageWindow(message,dialogueUrl);
			}
			else if (value.data != value.targetName){
				var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=MessageWindow";
				messageWindow("The domain name '"+value.targetName+"' is already being used on WebSketch.  Please enter a different domain name.",dialogueUrl);
			
			}
		}else{			
			



			if (responseStr.replace(/^\s*$/g,'') =="" || responseStr=="null"){
				$(this).attr("class","notEditedLabel");
				
				
				
				var premiumFlag = $("#easyurl").val();
				
				var newUrl = "";
				var easyDomain = "";
				if (premiumFlag == "1" ){
						easyDomain = $("#bigImageEasyUrlMarkup p").attr("name");
						easyDomain = easyDomain.replace(/\/$/,"");
						var screenName = $("#bigImageEasyUrlMarkup p").attr("rel");
						//set new domain
						$("#bigImageEasyUrlMarkup p").attr("name",$("#thickboxContext").val().replace("www",screenName));
						newUrl =  $("#bigImageEasyUrlMarkup a").attr("href").replace(easyDomain,$("#thickboxContext").val().replace("www",screenName).replace(/\/$/,""));
					
				}else{
						easyDomain = $("#bigImageEasyUrlMarkup p").attr("name");
						easyDomain = easyDomain.replace(/\/$/,"");
						//set new domain
						$("#bigImageEasyUrlMarkup p").attr("name",$("#thickboxContext").val());
						newUrl =  $("#bigImageEasyUrlMarkup a").attr("href").replace(easyDomain,$("#thickboxContext").val().replace(/\/$/,""));
					
				}
				

						//when domain is empty, the url should contain site title
						//if sitetitle is empty, then use site id.						
						//var titleSlug = $("#bigImageTitleMarkup h2").attr("name");
						var titleSlug=value.slugName;
						//the domain value is changed, so need to reget it.
						easyDomain = $("#bigImageEasyUrlMarkup p").attr("name");
						easyDomain = easyDomain.replace(/\/$/,"");
						newUrl = newUrl.replace(easyDomain+"/"+titleSlug,easyDomain);
						newUrl = newUrl.replace(easyDomain,easyDomain+"/"+titleSlug);
						
						 $("#bigImageEasyUrlMarkup a").attr("href",newUrl);
						 $("#bigImageEasyUrlMarkup a").html(newUrl);
						sitesPage.updateBigThumbnailUrlByManual(newUrl);
						
			}else{
				$(this).attr("class","hasBeenEditedLabel");
				var domainReg =  /^(\w)+\.(\w)+\.(\w)+$/;

				if (false == domainReg.test(responseStr)){
					responseStr = "www."+responseStr;
				}
				
				
				
						//update the easy url link
						var easyDomain = $("#bigImageEasyUrlMarkup p").attr("name");
						easyDomain = easyDomain.replace(/\/$/,"");
						$("#bigImageEasyUrlMarkup p").attr("name","http://"+responseStr+"/");
						var newUrl =  $("#bigImageEasyUrlMarkup a").attr("href").replace(easyDomain,"http://"+responseStr);
						
						//when domain is available, the url shouldn't contain site 
						//title any more
						//var titleSlug = $("#bigImageTitleMarkup h2").attr("name");
						var titleSlug=value.slugName;
						newUrl = newUrl.replace("/"+titleSlug,"");
						
						
						 $("#bigImageEasyUrlMarkup a").attr("href",newUrl);
						 $("#bigImageEasyUrlMarkup a").html(newUrl);

						sitesPage.updateBigThumbnailUrlByManual(newUrl);
		
				
				
			}
		}
	}
	});	
	
	var pagenameBarHeight = 21;
	
	if (document.all){
		pagenameBarHeight = 19;
	}
	
	$("#big_image_pageName .inline-edit h2").editable(ws_ajax_path_prefix+"changeTitle",{
	onblur:'submit',
	dataType:'json',
	ajaxType:'jsonp',
	charLimit:30,
	width:'98%',
	height:pagenameBarHeight,
	onkeyup:function (inputHandle) {	
			textLimit(inputHandle,30);
			//charLimit(inputHandle);
		},
    cssclass : "editableSingleLinePageName", 
	placeholder:'( Click here to add a title )',
	callback:function (value,settings){
		//Util.log(value);
		var responseStr = value.slugName;
		var plainPageName = value.data;
		
		if (value.error != null && value.error != ""){
			
			//There shouldn’t be an error message for the case when the value after you click is the same as before.
			if (value.data != value.targetName){
			
				var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=MessageWindow";
				messageWindow("You already have a page titled '"+value.targetName+"'.  Please give a unique page name for this site.",dialogueUrl);
			
			}
		}else{	
			if (responseStr.replace(/^\s*$/g,'') =="" || responseStr=="null"){
				//$(this).attr("class","notEditedLabel");			
				$("#big_image_pageName .inline-edit h2").html($(this).attr("name"));
			}else{
				$(this).attr("class","hasBeenEditedLabel");			
				sitesPage.updateUrlAfterChanged(responseStr,$(this).attr("name"));
				sitesPage.updateListAfterChanged(plainPageName,$(this).attr("id").replace("n",""));
				$(this).attr("name",responseStr);
			}
		}		
		
		
		
		
	}
	});	
	
	
	$(".nextBigPage").click(function (){
									  
									  
	});
	
	
}
	

function iframeActionListener(){
	var ifr = $("#TB_iframeContent");
	
	if (window.location.href.indexOf("leave") >-1 ){
		
		window.clearInterval(global_timer_ifr);
		tb_remove();
	}
	
};

var global_timer_ifr = null;

function checkshare(handle,privacy){
	var context = $(handle).attr("rel");
	
		var path = $(handle).attr("name");
		if (global_privacy != -1){
			privacy = global_privacy;
		}
		var ws_ajax_path_prefix = $("#thickboxContext").val();
	
		
		var crossUs = false;

		
		var trackUrl = window.location.href.replace("http://","");		
		$.getJSON(ws_ajax_path_prefix+"session?ss=ss&callback=?",
		//  $.getJSON("/session?callback=?",
					  function(json){
								ws_ajax_path_prefix = "http://"+window.location.host+"/";
							
								 if (json.session=="true") {
									var a = ws_ajax_path_prefix+path;
									
									if (crossUs){
										a += "&trackUrl="+trackUrl;
										a += "&TB_iframe=true";
										a = a.replace("shareNote","shareNoteIfr");
										//global_timer_ifr = window.setInterval(iframeActionListener,200);
									}
									
									tb_initForce(a ,400);
								}else {
									if (privacy!=3){
										
										window.location=$("#thickboxContext").val()+"login";
									}else{
										
										var a = ws_ajax_path_prefix+path;
										if (crossUs){
											a += "&trackUrl="+trackUrl;
											a += "&TB_iframe=true";
											a = a.replace("shareNote","shareNoteIfr");
											//global_timer_ifr = window.setInterval(iframeActionListener,200);
										}
										tb_initForce(a ,400);
									}	
								}
						}
				);			
	
		
	/*	
		$.ajax({url:context+"session",
                 type: 'GET',
                 dataType: 'json',
                 timeout: 10000,
                 error: function(){ 
                 },
                success:function(json){
                //alert(json.session);
                 if (json.session=="true") {
					var a = context+path;
				    tb_initForce(a ,400);
                }else {
                	if (privacy!=3){
                		//alert(privacy);
						window.location=context+"login";
					}else{
						var a = context+path;
				    	tb_initForce(a ,400);
					}	
				}
		}
		});
		
	*/	
}


function GallerySort (type,order){
	/*
	if (global_imgsrcArray == null){
		global_imgsrcArray = new Array();
		for (var i=0;;i++){
			try{
				global_imgsrcArray.push($("thumbTop"+i).attr("src"));
			}catch(e){
				break;
			}
		
		}
	}
	*/
	
	if (type == null || type == ""){
		alert("please select a method to sort first");
	}
	
	var ws_ajax_path_prefix = $("#thickboxContext").val();
	var ws_ajax_host  =  window.location.host;
	var extURLValue = $("#extURL").val();
	var query = "&type="+type+"&order="+order+"&extURL="+extURLValue;
	
	//avoid doing the same sorting again
	if (global_lastQuery != null ){		
		if (global_lastQuery == query){
			return;
		}else{
			global_lastQuery = query;
		}
	}else{
		global_lastQuery = query;
	}
	
	query = "antiCache="+((new Date()).getTime())+query;
	
	$.getJSON(ws_ajax_path_prefix+"changeSite?"+query+"&callback=?",
			   function(json){
				if (json != "") {
	                
	                var results = json.results;
	                var pagesCount = results.length;
		                if (results!=null){	
		                			for (var i=0;i<pagesCount;i++){
										$("#thumbTop"+i).attr("src",results[i].imgsrc);
										$("#thumbTop"+i).attr("title",results[i].title);
										$("#thumbTop"+i).parent().attr("id","thumb"+results[i].id);
										if(results[i].siteType=='01')
											$("#thumbTop"+i).parent().parent().parent().attr("class","thumb_wrapper thumb");
										if(results[i].siteType=='02')
										    $("#thumbTop"+i).parent().parent().parent().attr("class","thumb_wrapper thumb multi");
									}	
									//after reorder the images, we should update the  position for the 
									// glowing thumbnail  
									var glowingId = $("#currentThumbSnoteId").text();
									if (glowingId != null && glowingId != ""){
										$("#thumb"+glowingId).click();
												$.each($.find(".thumb_selected"), function(){
													sitesPage.deselectThumb($(this));
												});
												
												//change the selected thumbnail border to blue
												$.each($("#thumb"+glowingId).parent().parent().find(".thumb_border"), function() {
													sitesPage.selectThumb($(this));
												});
										
									}
		                }
	                }//end if
			   }
			);		
	
	/*
		$.ajax({url:ws_ajax_path_prefix+"changeSite?"+query,
                 type: 'GET',
                 dataType: 'json',
                 timeout: 10000,
                 error: function(){ 
                 },
                success:function(json){
	                if (json != "") {
	                
	                var results = json.results;
	                var pagesCount = results.length;
		                if (results!=null){	
		                			for (var i=0;i<pagesCount;i++){
										$("#thumbTop"+i).attr("src",results[i].imgsrc);
										$("#thumbTop"+i).attr("title",results[i].title);
										$("#thumbTop"+i).parent().attr("id","thumb"+results[i].id);
										if(results[i].siteType=='01')
											$("#thumbTop"+i).parent().parent().parent().attr("class","thumb_wrapper thumb");
										if(results[i].siteType=='02')
										    $("#thumbTop"+i).parent().parent().parent().attr("class","thumb_wrapper thumb multi");
									}	
									//after reorder the images, we should update the  position for the 
									// glowing thumbnail  
									var glowingId = $("#currentThumbSnoteId").text();
									if (glowingId != null && glowingId != ""){
										$("#thumb"+glowingId).click();
												$.each($.find(".thumb_selected"), function(){
													sitesPage.deselectThumb($(this));
												});
												
												//change the selected thumbnail border to blue
												$.each($("#thumb"+glowingId).parent().parent().find(".thumb_border"), function() {
													sitesPage.selectThumb($(this));
												});
										
									}
		                }
	                }
				}
		});
	//a data
	
	*/
	
}	
 	
 var sitesPage = {
 	currentId : 0,
 	currentPageId:0,
 	self : this,
 	bindRadioClick: function(){
 	
	 	 currentId = $("#currentThumbSnoteId").html();
		$(".privacyRadioWrapper input").unbind().click(function(){
			
			var thisId = $(this).attr("id"); 
			sitesPage.updatePrivacySettings(thisId,currentId);
			
		});
	
 	},
 	bindCheckClick: function(){
 	
	 	 currentId = $("#currentThumbSnoteId").html();
	 	 currentPageId = $("#currentThumbPageId").html();
		$("#homeCheckBox").unbind().click(function(){
			
			var thisChecked = $("#homeCheckBox:checked").val(); 
			if (thisChecked == null){
				thisChecked = false;	
			}else{
				thisChecked = true;	
			}
			var snoteId = $("#currentThumbSnoteId").text();
			var pageId = $("#currentThumbPageId").text();
			sitesPage.updateHomePageSettings(thisChecked,snoteId,pageId);
			// update the page navigation arrows
			$(".prevBigPage a").addClass("disable");
			$(".prevBigPage a").parent().addClass("disable");	
			
			$(".nextBigPage a").removeClass("disable");
			$(".nextBigPage a").parent().removeClass("disable");
			
			//update the page name dropdown list
			//PageTitleSelect
		
			
			$("#PageTitleSelect").prepend($("#ws_t"+pageId).parent());
			//$("#PageTitleSelect").remove();
			
			//update small thumbnail
			if ($(this).val() != ""){
				$("#thumb"+snoteId+" img").attr("src",$(this).val());
			
			}
		});
	
 	},
	updateUrlAfterChanged:function (pageName,originalName){
		var originalUrl = $("#bigMainImage a").attr("href");
		originalUrl = originalUrl.replace ("/"+originalName,"/"+pageName);
		
		$("#bigMainImage a").attr("href",originalUrl);
		$(".bigImageSiteLinks .viewRow a").attr("href",originalUrl);
		
		var originalEasyUrl = $("#bigImageEasyUrlMarkup a").attr("href");
		
		var easyUrlPageNameReg=new RegExp("/"+originalName+"$");
		
		originalEasyUrl = originalEasyUrl.replace(easyUrlPageNameReg,"/"+pageName);
		
		$("#bigImageEasyUrlMarkup a").attr("href",originalEasyUrl);
		
		$("#bigImageEasyUrlMarkup a").html(originalEasyUrl);
	},
	updateUrlAfterTitleChanged:function (siteTitle,originalName){
		var originalUrl = $("#bigMainImage a").attr("href");
		
		
		var siteTitleReg=new RegExp("/"+originalName);
		
		originalUrl = originalUrl.replace(siteTitleReg,"/"+siteTitle);
		$("#bigMainImage a").attr("href",originalUrl);
		$(".bigImageSiteLinks .viewRow a").attr("href",originalUrl);

	},
	updateBigThumbnailUrlByManual:function (newUrl){
		$("#bigMainImage a").attr("href",newUrl);
		$(".bigImageSiteLinks .viewRow a").attr("href",newUrl);

	},		
	updateSiteTitle:function (title){
		$("#bigMainImage a img").attr("title",title);
		var selectedSite = $("#currentThumbSnoteId").text();
		$("#thumb"+selectedSite+" img").attr("title",title);
	},		
		
	
	updateListAfterChanged:function (pageName,id){
		$("#ws_t"+id).html(pageName);
	},	
 	updateHomePageSettings: function(thisChecked,snoteId,currentPageId){
	var ws_ajax_path_prefix = $("#thickboxContext").val();
	var ws_ajax_host  =  window.location.host;
		var message = "snoteid=" + snoteId
					+ "&thisChecked="+thisChecked
					+ "&currentPageId="+currentPageId
					+ "&timeCache="+(new Date().getTime());
					
	$.getJSON(ws_ajax_path_prefix+"homePageSet?"+message+"&callback=?",
				   function(json){

				   }
				);						
		
		/*
		$.ajax({
		type:"POST"
		,url:ws_ajax_path_prefix+"homePageSet?"+message
		,async:true
		,data:message
		,contentType:"application/x-www-form-urlencoded;charset=UTF-8"
		});
		*/

	},
	updatePrivacySettings: function(newPrivacy,snoteId){
	var ws_ajax_path_prefix = $("#thickboxContext").val();
	var ws_ajax_host  =  window.location.host;
		var message = "snoteid=" + snoteId
					+ "&privacyLevel="+newPrivacy;
		
		
	$.getJSON(ws_ajax_path_prefix+"privacyRadio?"+message+"&callback=?",
				   function(json){

				   }
				);			
		/*			
		$.ajax({
		type:"POST"
		,url:ws_ajax_path_prefix+"privacyRadio"
		,async:true
		,data:message
		,contentType:"application/x-www-form-urlencoded;charset=UTF-8"
		});
		*/

	},
	updateBigImage: function(json){
    	var ws_ajax_path_prefix = $("#thickboxContext").val();
		var ws_ajax_host  =  window.location.host;
 
                	if ( json.isAuthor=="1" && (json.title == "null" || json.title.replace(/^\s*$/g,'') == "")){
                		$("#bigImageTitleMarkup h2").html("( Click here to add a site title )");                	
                		$("#bigImageTitleMarkup h2").attr("class","	notEditedLabel");
						
						$("#bigImageTitleMarkup h2").attr("name",json.id);
                	}else{
                		$("#bigImageTitleMarkup h2").html(json.title);                    		          	
                		$("#bigImageTitleMarkup h2").attr("class","	hasBeenEditedLabel");
						
						$("#bigImageTitleMarkup h2").attr("name",json.titleSlug);
						
                	}
              	
                	
					Util.log(json.description);
					
                	if ( json.isAuthor=="1" && (json.description == "null" || json.description.replace(/^\s*$/g,'') == "")){
                		$("#bigImageDescMarkup p").html("( Click here to add a description )");                	
                		$("#bigImageDescMarkup p").attr("class","	notEditedLabel");
                	}else{
                		//$("#bigImageDescMarkup p").html(json.description.replace(/<br>/g,"<br>\n"));  
                		$("#bigImageDescMarkup p").html(json.description);                		              	
                		$("#bigImageDescMarkup p").attr("class","	hasBeenEditedLabel");
                	}     
                	
                  	if ( json.isAuthor=="1" && (json.keywords == "null" || json.keywords.replace(/^\s*$/g,'') == "")){
                		$("#bigImageKeywordsMarkup p").html("( Click here to add a keyword )");                	
                		$("#bigImageKeywordsMarkup p").attr("class","	notEditedLabel");
                	}else{
                		$("#bigImageKeywordsMarkup p").html(json.keywords);                	
                		$("#bigImageKeywordsMarkup p").attr("class","	hasBeenEditedLabel");
                	}      
                	
                   	if ( json.isAuthor=="1" && (json.tags == "null" || json.tags.replace(/^\s*$/g,'') == "")){
                		$("#bigImageTagsMarkup p").html("( Click here to add tags )");                	
                		$("#bigImageTagsMarkup p").attr("class","	notEditedLabel");
                	}else{
                		$("#bigImageTagsMarkup p").html(json.tags);                	
                		$("#bigImageTagsMarkup p").attr("class","	hasBeenEditedLabel");
                	}      
					if(json.siteOwerIsDomainMapping!="0"){
					  	if ( json.isAuthor=="1"  && (json.domainUrl == "null" || json.domainUrl.replace(/^\s*$/g,'') == "")){
	                		$("#bigImageDomainMarkup p").html("( Click here to add a domain name )");                
							$("#domainMappingArea a").html("Add domain mapping");
							$("#domainMappingArea a").attr("class","notEditedLabel");
							$("#domainMappingArea span").html("");
							
	                		$("#bigImageDomainMarkup p").attr("class","	notEditedLabel");
							if ($("#easyurl").val() == "1"){
								
								$("#bigImageEasyUrlMarkup p").attr("name",$("#thickboxContext").val().replace("www",json.screenName));	
							}else{
								$("#bigImageEasyUrlMarkup p").attr("name",$("#thickboxContext").val());	
							}
	                	}else{
	                		var domainUrlTep="";
							if ($("#easyurl").val() == "1"){
								var domainReg =  /^(\w)+\.(\w)+\.(\w)+$/;
								if (false == domainReg.test(json.domainUrl) && json.domainUrl != "null" && json.domainUrl.replace(/^\s*$/g,'') != ""){
									//json.domainUrl = "www."+json.domainUrl;
									domainUrlTep = "www."+json.domainUrl;
								}else{
									domainUrlTep =json.domainUrl;
								}
								//$("#bigImageEasyUrlMarkup p").attr("name","http://"+json.domainUrl+"/");	
								$("#bigImageEasyUrlMarkup p").attr("name","http://"+domainUrlTep+"/");
							}else{
								$("#bigImageEasyUrlMarkup p").attr("name",$("#thickboxContext").val());	
							}
							
	                		//$("#bigImageDomainMarkup p").html(json.domainUrl);                	
							$("#domainMappingArea a").html("Edit domain mapping");
							$("#domainMappingArea a").attr("class","editted");
							$("#domainMappingArea span").html(domainUrlTep);
							
	                		//$("#bigImageDomainMarkup p").attr("class","	hasBeenEditedLabel");	
	                	}  
					}
					
                if(json.siteMultipageSites!="0"){	               	          	
                	
                	if ( json.isAuthor=="1" && (json.pageName == "null" || json.pageName.replace(/^\s*$/g,'') == "")){
                		$("#big_image_pageName h2").html("Untitled"); 	
						$("#big_image_pageName h2").attr("name","Untitled");
                		$("#big_image_pageName h2").attr("class","	notEditedLabel");
                	}else{
						
						if(json.pageName == "" && json.sitetype=="01"){
							json.pageName = "Home";	
						}
                		$("#big_image_pageName h2").html(json.pageName);                    		          				$("#big_image_pageName h2").attr("name",json.pageSlug);
                		$("#big_image_pageName h2").attr("class","	hasBeenEditedLabel");
                	} 
                	$("#big_image_pageName h2").attr("id","n"+json.pageId);
                }	     
                	//update related value     
                	//alert(json.largeLink);
                	$("#bigImageEasyUrlMarkup a").html(json.largeLink);  
					$("#bigImageEasyUrlMarkup a").attr("href",json.largeLink);  
					
                	$("#bigMainImage a").attr("href",json.largeLink);           	
                	$("#bigMainImage img").attr("src",json.largeUrl);
                	
                	if (json.title == ""){
                		$("#bigMainImage img").attr("title","Untitled");
                	}else{
                		$("#bigMainImage img").attr("title",json.title);
                	}
                	$("#bigImageTitleMarkup h2").attr("id","t"+json.id);
					//$("#big_image_pageName h2").attr("id","n"+json.pageId);
                	$("#bigImageDescMarkup p").attr("id","d"+json.id);
                	$("#bigImageKeywordsMarkup p").attr("id","k"+json.id);
                	$("#bigImageTagsMarkup p").attr("id","g"+json.id);
                	$("#bigImageDomainMarkup p").attr("id","u"+json.id);
                	var oriShareName = $(".bigImageSiteLinks .shareRow a").attr("name");
                	
		            if(oriShareName){
		            	if(json.privacy=="3")
		            	 	$(".bigImageSiteLinks .shareRow").show();
		            	else if(json.isAuthor!="1")
		            	    $(".bigImageSiteLinks .shareRow").hide();
		            	 $(".bigImageSiteLinks .shareRow a").attr("name",oriShareName.replace(/note=(\d*)?/g,"note="+json.id));
		            }
		           
		          			                	
		            $(".bigImageSiteLinks .duplicateRow a").attr("name","dashboard?duplicate="+json.id);
		            
					 $(".bigImageSiteLinks .duplicateRow a").attr("onclick","");
		             $(".bigImageSiteLinks .duplicateRow a").unbind("click");
					 $(".bigImageSiteLinks .duplicateRow a").click(function(){
					
						checkAddPage(this,json.isFull);
					
					});
	
         		    $(".big_image_date").html(json.time);
         		    
//  					$("#pageViews").html(json.pageViews);
//				   if ( json.isAuthor=="1"){
//	                   // var siteId=$("#currentThumbSnoteId").html();
//	                    var pagePathURL = $("#thickboxContext").val()+"gcharts?siteId="+json.id+"&pageId="+json.pageId;
//                		$("#siteAnalyticsMarkup a").attr("href",pagePathURL);                	
//                	}  
				
                  if ( json.isAuthor=="1" && json.changePageViews=="1"){
						$("#pageViews").html(json.pageViews);
					}
//						$("#visitors").html(json.visitors);
//						$("#uniqueVisitors").html(json.uniqiueVisits);
						
//						if(json.domainUrl == "null" || json.domainUrl.replace(/^\s*$/g,'') == "" || json.isAddTruckCode=="0"){ 
//						   $("#bigVisitorMarkup").attr("style","");
//						   $("#visitors").attr("style","display:none;");
//						   $("#uniqueVisitors").attr("style","display:none;");
//						   
//						   $("#LevelChange").attr("style","display:none;");
//						   $("#LevelHide").attr("style","display:none;");
//						 }else
//						 {
//						   $("#visitors").attr("style","");
//						   $("#uniqueVisitors").attr("style","");
//						   $("#bigVisitorMarkup").attr("style","display:none;");
//						   $("#LevelChange").attr("style","");
//						   $("#LevelHide").attr("style","display:none;");
//						 }
//						   
//                	}  
                	
                	if(json.sitetype=="02")
                	{
            	        $(".bigImageSiteLinks .editRow a").attr("name","editor?note="+json.id+"&pageId="+json.pageId);
            	        //$(".bigImageSiteLinks .editRow a").attr("onclick","checkEditPage(this,"+json.currPageLargeTotal+")");
 
                	    //$(".bigImageSiteLinks .editRow a").attr("href",ws_ajax_path_prefix+"editor?note="+json.id+"&pageId="+json.pageId);
		                $(".bigImageSiteLinks .viewRow a").attr("href",json.largeLink);
		                $(".bigImageSiteLinks .deleteRow a").attr("name","deleteWarning?type=multi&delete="+json.id);
		               if(json.siteMultipageSites!="0"){	
			                if(json.homePageCheck=="1")
			                 $("#homeCheckBox").attr("checked","checked");
			                else
			                 $("#homeCheckBox").attr("checked","");
			                 
							 $("#homeCheckBox").val(json.smallUrl);
							 
							 
							   //multi pages site
							  $(".main_img_wrapper").addClass("multiBig");
							  $(".singleBig").removeClass("singleBig");
		                 }
		          


                	}else
                	{
                	    $(".bigImageSiteLinks .editRow a").attr("name","editor?note="+json.id+"&pageId="+json.pageId);
            	        //$(".bigImageSiteLinks .editRow a").attr("onclick","checkEditPage(this,"+json.currPageLargeTotal+")");
                	
                	    //$(".bigImageSiteLinks .editRow a").attr("href",ws_ajax_path_prefix+"editor?note="+json.id);
		                $(".bigImageSiteLinks .viewRow a").attr("href",json.largeLink);
		                $(".bigImageSiteLinks .deleteRow a").attr("name","deleteWarning?type=gallery&delete="+json.id);
						//single page site
						 if(json.siteMultipageSites!="0"){	
						$(".main_img_wrapper").removeClass("multiBig");
						
						$(".browse_main").addClass("singleBig");
						}
		            }
                	
					//update page name list
					$("#PageTitleSelect").hide();
					$("#PageTitleSelect").html("");
					var untitledIndex = 1;
					if (json.pageList != null && json.pageList.length>0){
						for (var pi = 0; pi<json.pageList.length;pi++){
							if (json.pageList[pi].name == "null" || json.pageList[pi].name == ""){
								json.pageList[pi].name = "Untitled "+untitledIndex;
								untitledIndex++;
							}
							//tid=thumb117741228790648477&pid=385921228790648477&type=next
							$("#PageTitleSelect").append("<li class=\"ws_option\"><a id=\"ws_t"+json.pageList[pi].id+"\" href=\"#\"  rel=\"tid=thumb"+json.id+"&pid="+json.pageList[pi].id+"&type=cur\">"+json.pageList[pi].name+"</a></li>");
						}					
					}else {
						$("#PageTitleSelect").append("<li class=\"ws_option\"><a id=\"ws_t"+json.pageId+"\" href=\"#\"  rel=\"tid=thumb"+json.id+"&pid="+json.pageId+"&type=cur\">"+json.pageName+"</a></li>");
					}
					$("#PageTitleSelect a").click(function (){
						$(".selectbox").hide();									
															
						var query = "antiCache="+((new Date()).getTime())+"&"+$(this).attr("rel")+"&path="+ws_ajax_host;
					
					$.getJSON(ws_ajax_path_prefix+"sac?"+query+"&callback=?",
							   function(json){
								  if (json != "") {												
												sitesPage.updateBigImage(json);
												
											}
							   }
							);							
					/*
						$.ajax({url:ws_ajax_path_prefix+"sac?"+query,
								 type: 'GET',
								 dataType: 'json',
								 timeout: 10000,
								 error: function(){ 
								 },
								success:function(jsonObj){
									if (jsonObj != "") {
										sitesPage.updateBigImage(jsonObj);
										
									}
								}
						});
					*/	
						
						
												  
					});	//end click function				
					
					
					
					//set currpageid
					$("#currentThumbPageId").html(json.pageId);
					//handle page navigation
					$(".nextBigPage a").attr("ref","tid=thumb"+json.id+"&pid="+json.pageId+"&type=next");
					$(".prevBigPage a").attr("ref","tid=thumb"+json.id+"&pid="+json.pageId+"&type=pre");
					
					if (json.prePageLink != null && json.prePageLink.id != ""){
						$(".prevBigPage a").removeClass("disable");
						$(".prevBigPage a").parent().removeClass("disable");
					}else{
						$(".prevBigPage a").addClass("disable");
						$(".prevBigPage a").parent().addClass("disable");
					}
					
					if (json.nextPageLink != null && json.nextPageLink.id != ""){
						$(".nextBigPage a").removeClass("disable");
						$(".nextBigPage a").parent().removeClass("disable");
					}else{
						$(".nextBigPage a").addClass("disable");
						$(".nextBigPage a").parent().addClass("disable");
					}
					
                	//update privacy
                	$("#privacy_"+json.privacy).attr("checked","checked");   
                	global_privacy = json.privacy;             	
                	$("#currentThumbSnoteId").html(json.id); 
                	this.bindRadioClick();		
	},
	//change thumbnail border to grey
	deselectThumb: function(thumb_div){
		$(thumb_div).css("background-image",$(thumb_div).css("background-image").replace(/hi/,"thumb"));
		$(thumb_div).removeClass("thumb_selected");
		$(thumb_div).addClass("thumb_border");
	},

	//change thumbnail border to blue
	selectThumb: function(thumb_div){
		$(thumb_div).css("background-image",$(thumb_div).css("background-image").replace(/thumb/,"hi"));
		$(thumb_div).removeClass("thumb_border");
		$(thumb_div).addClass("thumb_selected");
	},
	
	
	//hide custom select box
	hideSelectBox: function (){
	
	$(".selectbox").hide();
	}
};

function deletePage(){
			var context = $(".deleteRow a").attr("rel");	
			
			var query = $(".deleteRow a").attr("name")+"&deletesubmit=1";
	
		
		$.getJSON(context+query+"&callback=?",
				   function(json){
					  if (json != "") {
									Util.log(json);
									
									window.location.reload(true);							
								}
					  tb_remove();
				   }
				);	
}

function popupAddDomain(){
	var selctedOption = $(".hasDomainRadio").filter(":checked").val();
	if ( selctedOption == "1"){
			$("#domainStep1").hide();	
			
			//for some users have very small screen,
			//he may not see the complete panel of domainStep2
			//so,using js to adjust the top dynamicly according to the footer's top
			var footerTop = $("#footerZoneSites").offset().top;
			$("#domainStep2").show();
			var panelTop = $("#TB_window").offset().top;
			var panelHeight = $("#TB_window").height();
			
			var offsetTop = (panelTop + panelHeight) - (footerTop - 10);

			if ( offsetTop > 0){
					if ( offsetTop < panelTop){
						$("#TB_window").css("top",panelTop - offsetTop);
					}else{
						$("#TB_window").css("top",1);
					}
			}
			var ws_ajax_path_prefix = $("#thickboxContext").val();
			$("#domainDetail").attr("href","http://free-webpage.websketch.com/Domains/GoDaddy");
			
			$("#btnDomainAdd").show();
			$("#btnDomainNext").hide();	
		
	}else{
		window.open("http://free-webpage.websketch.com/Domains/DomainPurchase",'newwindow');
		tb_remove();
	}
	
	
	
	

}
function addDomain(url,addtype){

	var address;
	var domainEditType="";
	if (url != null){
		address = url;
		if (url == ""){
			domainEditType = "remove";
		}else{
			domainEditType = "edit";
		}
		//tb_remove();
	}else{
		 address = $("#iptDomainAddress").val();
		 domainEditType = "add";
		 if (address.replace(/^\s*$/g,'') =="" || address=="null"){
			$(".errorInfo").html("Please enter a domain before clicking Add.");		
			$(".errorInfo").show();	
			return false;
		}else{
			//tb_remove();
		}
	}

	
	
	
	//contructing ajax query url
	var ws_ajax_path_prefix = $("#thickboxContext").val();
	var domainAjaxUrl = "changeTitle?value="+address+"&id=u"+$("#currentThumbSnoteId").text()+"&callback=?";
	$.getJSON(ws_ajax_path_prefix+domainAjaxUrl,function(value) {
		Util.log(value);
		var responseStr = value.data;
		if (value.error != null && value.error != ""){
		     
			var message=value.error;
			if(message.indexOf("domain mappings")>1)
			{
				//var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=MessageWindow";
				//messageWindow(message,dialogueUrl);
				if (domainEditType == "add"){
					$("#domainAddError").html(message);
					$("#domainAddError").show();
				}else{
					$("#domainEditError").html(message);
					$("#domainEditError").show();
				}
				
				
				
			}
			else if (value.data != value.targetName){
				//var dialogueUrl = "#TB_inline?height=150&width=400&inlineId=MessageWindow";
				//messageWindow("The domain name '"+value.targetName+"' is already being used on WebSketch.  Please enter a different domain name.",dialogueUrl);
				message = "The domain name '"+value.targetName+"' is already being used on WebSketch.  Please enter a different domain name.";
				if (domainEditType == "add"){
					$("#domainAddError").html(message);
					$("#domainAddError").show();
				}else{
					$("#domainEditError").html(message);
					$("#domainEditError").show();
				}
				
			
			}
		}else{			
			   if (value.changePageViews=="0"){
						$("#pageViews").html(value.pageViews);
						var sId=$("#currentThumbSnoteId").text();
						$("#thumb"+sId).attr("pageview",value.pageViews);
					}

			if (responseStr.replace(/^\s*$/g,'') =="" || responseStr=="null"){
				$("#domainMappingArea a").attr("class","notEditedLabel");
				
				
				
				var premiumFlag = $("#easyurl").val();
				
				var newUrl = "";
				var easyDomain = "";
				if (premiumFlag == "1" ){
						easyDomain = $("#bigImageEasyUrlMarkup p").attr("name");
						easyDomain = easyDomain.replace(/\/$/,"");
						var screenName = $("#bigImageEasyUrlMarkup p").attr("rel");
						//set new domain
						$("#bigImageEasyUrlMarkup p").attr("name",$("#thickboxContext").val().replace("www",screenName));
						newUrl =  $("#bigImageEasyUrlMarkup a").attr("href").replace(easyDomain,$("#thickboxContext").val().replace("www",screenName).replace(/\/$/,""));
					
				}else{
						easyDomain = $("#bigImageEasyUrlMarkup p").attr("name");
						easyDomain = easyDomain.replace(/\/$/,"");
						//set new domain
						$("#bigImageEasyUrlMarkup p").attr("name",$("#thickboxContext").val());
						newUrl =  $("#bigImageEasyUrlMarkup a").attr("href").replace(easyDomain,$("#thickboxContext").val().replace(/\/$/,""));
					
				}
				

						//when domain is empty, the url should contain site title
						//if sitetitle is empty, then use site id.						
						//var titleSlug = $("#bigImageTitleMarkup h2").attr("name");
						var titleSlug = value.slugName;
						//the domain value is changed, so need to reget it.
						easyDomain = $("#bigImageEasyUrlMarkup p").attr("name");
						easyDomain = easyDomain.replace(/\/$/,"");
						newUrl = newUrl.replace(easyDomain+"/"+titleSlug,easyDomain);
						newUrl = newUrl.replace(easyDomain,easyDomain+"/"+titleSlug);
						
						 $("#bigImageEasyUrlMarkup a").attr("href",newUrl);
						 $("#bigImageEasyUrlMarkup a").html(newUrl);
						sitesPage.updateBigThumbnailUrlByManual(newUrl);
						
						//remove mapped domain
						$("#domainMappingArea span").html("");
						$("#domainMappingArea a").html("Add domain mapping");	
						
						//update domain count
						var domainMappingCount = Number($("#domainMappingCount").val())+1;
						$("#domainMappingCount").val(domainMappingCount);
						
						//pageview
//						   $("#bigVisitorMarkup").attr("style","");
//						   $("#pageViews").html("views: 0");
//						   $("#visitors").attr("style","display:none;");
//						   $("#uniqueVisitors").attr("style","display:none;");
//						   
//						   $("#LevelChange").attr("style","display:none;");
//						   $("#LevelHide").attr("style","display:none;");
						   
						$(".errorInfo").hide();		
						tb_remove();
						
			}else{
				$("#domainMappingArea a").attr("class","editted");
				var domainReg =  /^(\w)+\.(\w)+\.(\w)+$/;
				if (false == domainReg.test(responseStr)){
				   var dateArray = new   Array();     
					dateArray=responseStr.split(".")
					if(dateArray.length<3)
					  responseStr = "www."+responseStr;
				}
				        //pageview visitor unvisitor
				        // 
//				      var sonteId  =  $("#currentThumbSnoteId").html();
//				        $("#pageViews").html("Views: (Domain stats are unavailable for 24-48 hours after a domain switch.)");
//				        $("#pageViews"+sonteId).html("Views = TBD");
//				        
//				         $("#bigVisitorMarkup").attr("style","");
//						   $("#visitors").attr("style","display:none;");
//						   $("#uniqueVisitors").attr("style","display:none;");
//						   
//						   $("#LevelChange").attr("style","display:none;");
//						   $("#LevelHide").attr("style","display:none;");
						   
						   
//						   $("#visitors").attr("style","");
//						   $("#uniqueVisitors").attr("style","");
//						   $("#bigVisitorMarkup").attr("style","display:none;");
//						   $("#LevelChange").attr("style","");
//						   $("#LevelHide").attr("style","display:none;");
				
						//update the easy url link
						var easyDomain = $("#bigImageEasyUrlMarkup p").attr("name");
						easyDomain = easyDomain.replace(/\/$/,"");
						$("#bigImageEasyUrlMarkup p").attr("name","http://"+responseStr+"/");
						var newUrl =  $("#bigImageEasyUrlMarkup a").attr("href").replace(easyDomain,"http://"+responseStr);
						
						//when domain is available, the url shouldn't contain site 
						//title any more
						//var titleSlug = $("#bigImageTitleMarkup h2").attr("name");
						var titleSlug=value.slugName;
						newUrl = newUrl.replace("/"+titleSlug,"");
						
						
						 $("#bigImageEasyUrlMarkup a").attr("href",newUrl);
						 $("#bigImageEasyUrlMarkup a").html(newUrl);

						sitesPage.updateBigThumbnailUrlByManual(newUrl);
		
						$("#domainMappingArea span").html(responseStr);
						$("#domainMappingArea a").html("Edit domain mapping");
						//update domain count
						var currNum= Number($("#domainMappingCount").val());
						if(currNum>0)
						var domainMappingCount = Number($("#domainMappingCount").val())-1;
						$("#domainMappingCount").val(domainMappingCount);						
						
						//hide error info field
						$(".errorInfo").hide();		
						tb_remove();
						
						
			}
		}
		
	});
	
	
	
	
	
	
}

function clear_errMsg()
	{
		$("#domainAddError").html("the domain field can not be empty!");
		$("#domainEditError").html("the domain field can not be empty!");
		$("#btnDomainAdd").hide();
		tb_remove();
	}
function modifyDomain(){
var ws_ajax_path_prefix = $("#thickboxContext").val();
	var selctedOption = $(".modifyDomainRadio").filter(":checked").val();
	if (selctedOption == 'redirect'){
	  window.location.href="http://free-webpage.websketch.com/Domains/DomainPurchase";
	}else if (selctedOption == 'empty'){
		addDomain("","remove");
	}else {
		var address = $("#iptDomainAddressEdit").val();
		if (address.replace(/^\s*$/g,'') ==""){
			$(".errorInfo").html("the domain field can not be empty!");		
			$(".errorInfo").show();		
			return false;	
		}
		addDomain(address);
	}
}
