//<![CDATA[ 
var isLoadGMap = false;
var mobileurl = "";
var previous = "";
var next = "";
var photoidtmp = "";
var useridtmp = "";
var owneridtmp = "";
var ismypagetmp = false;
var isMyPage_Group = false;
var page = "photo";
var commentpageno = 0;
var TitleEditor = null;
var DescriptionEditor = null;
var TagsEditor = null;
var PhotoPrivacy = null;
var imgdeleting = false;
var commentdeleting = false;
var isimgrotate = false;
var keyarray = new Array;
var valuearray = new Array;
var shadowbox_mac_loading_img = new Image();
shadowbox_mac_loading_img.src = '/static/v2p/images/shadowbox_mac_loading.gif';
var reloadpage = false;
var photofilename = "";
var rotating = false;
var fading = false;
var smallZoomControl;
var commentposting = false
var groupInfoList = {};
var hasBlog = false;
var blogUpdate = false;
var counter = 0;
var timeoutId = -1;
var locationlist;
var phototitle = "";
function updateLinkMenu(userid)
{
	$('afirstitem').href = "/profiles/" + userid;
	$('aseconditem').href = "/friends/" + userid;
	$('athirditem').href = "/photos/" + userid;
	$('afifthitem').href = "/videos/" + userid;
	$('asixthitem').href = "/maps/" + userid;
	$('blogitem').href = "/blog/" + userid;
    $('groupitem').href = "/groups/" + userid;
	$('avatarlink').href = "/profiles/" + userid;

	if(hasBlog){
		showElement('blogitem');
		if(blogUpdate)
			$('blogupdateitem').style.display='inline';
		else
			hideElement('blogupdateitem');
	}else
		hideElement('blogitem');
}

function gotoprev()
{
	if($('hprevious').value!='#')
	{
		showElement('loading');
		getphotodetail($('hprevious').value,false)
	}
}

function gotonext()
{
	if($('hnext').value!='#')
	{
		showElement('loading');
		getphotodetail($('hnext').value,false)
	}
}

function deleteimage()
{
		if(photoidtmp!='' && !imgdeleting)
		{
			if(confirm(_('Do you want to delete this photo?')))
			{
				imgdeleting = true;
				showElement('loading');
				var opt = {
					method: 'post',
					postBody: 'photoid=' + photoidtmp,
					onSuccess: function(t) {
						hideElement('loading');
						imgdeleting = false;
						if($('hnext') && $('hnext').value!='#')
							getphotodetail($('hnext').value,false);
						else
						{
							if($('hprevious') && $('hprevious').value!='#')
								getphotodetail($('hprevious').value,false);
							else
								window.location.href = "/photos/album/"+useridtmp;
						}
					},
					onFailure: function(t) {
						imgdeleting = false;
						hideElement('loading');
						alert(_("Sorry, Can't delete photo. Please, try again."));
					}
				}
				new Ajax.Request('/photo/deletephoto', opt);
			}
		}
}

function deletecomment_click(itemtype,itemid)
{
	if(itemid && !commentdeleting)
	{
		if(confirm(_('Do you want to delete this message?')))
		{
			commentdeleting = true;
			var opt = {
				method: 'post',
				postBody: 'type=' + itemtype + '&id=' + itemid,
				onSuccess: function(t) {
					commentdeleting = false;
					showcomments(photoidtmp,commentpageno);
				},
				onFailure: function(t) {
					commentdeleting = false;
					alert(_("Sorry, the message cannot be deleted. Please try again"));
				}
			};
			new Ajax.Request('/photos/deletePhotoComment', opt);
		}
	}
	else
	{
		if(commentdeleting)
			alert(_("Sorry, the message is deleting. Please wait"));
	}
}

function rotateimage(delta)
{
	if(photoidtmp=="")
		return;
	if(!rotating)
	{
		showElement('loading');
		rotating = true;
		var opt = {
			method: 'post',
			postBody: 'photoid=' + photoidtmp + '&delta=' + delta,
			onSuccess: function(t) {
				if(t.responseText != "error" && t.responseText!='')
				{
					var img = new Image()
						img.onload = function(){
						if(fading) fading.cancel();
						var imageview = $('imageview');
						imageview.setOpacity(0);
						imageview.src=this.src;
						fadeUp(1.0)
						this.onload = function(){};
						if (islandscape)
							islandscape=undefined;
					}
					img.src = staticpath+'/asset/photo/medium/' + getPhotoPath(useridtmp) +'/'+ t.responseText;

					$('img'+photoidtmp.toString()).src = staticpath+'/asset/photo/30x30/' + getPhotoPath(useridtmp)  + '/' + t.responseText;
					rotating = false;

					// crop avatar
					imgsrc = staticpath+'/asset/photo/medium/' + getPhotoPath(useridtmp) +'/'+ t.responseText;
					setCropAvatar(imgsrc);
				}
				else if(t.responseText == "error")
				{
					rotating = false;
					hideElement('loading');
					alert(_("Sorry, cannot rotate the picture. Please try again later"));
				}
			},
			onFailure: function(t) {
				rotating = false;
				hideElement('loading');
				alert(_("Sorry, cannot rotate the picture. Please try again later"));
			}
		}
		new Ajax.Request('/photo/rotate', opt);
	}
	else
		alert(_("Photo rotating. Please wait"));
}
function getphotodetail(photoid,firsttime)
{
	if(photoid.indexOf('i')==0)
		photoid = photoid.substring(1);
	if (!firsttime)
	{
		if(window.location.href.indexOf('/photo/view/link#')==-1)
		{
			window.location.href = "/photo/view/link#"+photoid;
			return;
		}
	}

	showElement('loading');
	if(!quickPostIndexPage) quickPostIndexPage = $('quickpost').innerHTML;
		quickPostIndex();
	if(TitleEditor)
	{
		if(TitleEditor._editing)
			TitleEditor.leaveEditMode();
	}

	if(DescriptionEditor)
	{
		if (DescriptionEditor._editing)
			DescriptionEditor.leaveEditMode();
	}

	/*if(TagsEditor)
	{
		if (TagsEditor._editing)
			TagsEditor.leaveEditMode();
	}*/
    var currentOpacity = $('imageview').getOpacity() || 0.0;
    if(currentOpacity > 0) fadeDown(0.0);

	var opt = {
			method: 'get',
			onSuccess: function(t) {
				if (t.responseText=='error')
					return;

				result = t.responseText.evalJSON();
				if(result.IsDeleted || result.CanNotShow)
				{
					if(result.CanNotShow)
						showElement('canshowmsg');
					else
						showElement('deletemsg');
					
					hideElement('itemtitle');
					hideElement('next');
					hideElement('previous');
					hideElement('map_section');
					hideElement('deleteimg');
					hideElement('loading');
					hideElement('imageview');
					hideElement('itemdetail');
					hideElement('sendimproper');
					hideElement('sharebox');
					hideElement('addcomment');
					hideElement("top_bar");
					hideElement("photoprivacy");
					hideElement("commentlist");
					hideElement("sharebox");
					hideElement('rotate90');
					hideElement('rotate270');
					hideElement('relatephoto');
					$('relatephoto').innerHTML = "";
					$('rotate90').onclick=function(){};
					$('rotate270').onclick=function(){};
					
					useridtmp = result.UserID
					if($('miniprofile'))
					{
						if($('miniprofile').innerHTML=='')
							loadMiniProfile(useridtmp);
					}
					if($('tagcloud'))
					{
						if($('tagcloud').innerHTML=='')
							loadTagCloud(useridtmp);
					}

					if($("shopInput"))
						hideElement('shopInput');

					updateLinkMenu(useridtmp);
					window.location.hash=photoid;
					return;
				}
				hideElement('canshowmsg');
				hideElement('deletemsg');
				showElement('itemtitle');
				showElement('imageview');
				showElement('itemdetail');
				showElement('share');
				showElement("commentlist");
				showElement('map_section');
				showElement("sharebox");
				if (result.relatephotos.length > 0)
				{
					var relatephoto="";
					relatephoto='<h3>'+_("Relate Photos")+'</h3>';
					for(var i=0;i<result.relatephotos.length;i++)
					{
							relatephoto+='<a href="/photo/view/'+result.relatephotos[i].id+'">';
							relatephoto+='<img src="http://static1.pg.in.th/asset/photo/50x50/'+getPhotoPath(result.relatephotos[i].userid)+'/'+result.relatephotos[i].filename+'"/>';
							relatephoto+='</a>';
					}
					$('relatephoto').innerHTML = relatephoto;
					showElement('relatephoto');
				}
				else
				{
					hideElement('relatephoto');
					$('relatephoto').innerHTML = "";
				}

				if (result.showStar && !result.showAddComment)
					hideElement('addcomment');
				else
					showElement('addcomment');
                
                $('useravatar').src = "/asset/avatar/44x44/" + result.avatarFilename;
				var reslist = result.photolist.split("|");
				var output = '';
					photoidtmp = photoid;
					
				var useridtmp = reslist[0];
				var ismypage2 = result.isMyPage

				if (ismypage2)
					showElement("photoprivacy");
				else
					hideElement("photoprivacy");

				for(var i = 1;i<reslist.length;i++)
				{
					if(reslist[i]!="")
					{
						if(reslist[i].indexOf('current')==-1)
						{
							var photoitem = reslist[i].split(':')
							output += '<a href="javascript:void(0);" id="i'+photoitem[0]+'" onclick="getphotodetail(this.id,false);" ><img id="img'+photoitem[0]+'"  class="avatar" style="cursor:pointer;" src="'+staticpath+'/asset/photo/30x30/'+getPhotoPath(useridtmp)+'/'+photoitem[1]+ '" alt="'+photoitem[0]+'"/></a>';
						}
						else
						{
							var currentview = reslist[i].substring(8);
							var photoitem = currentview.split(':');
							output += '<a href="javascript:void(0);" id="i'+photoitem[0]+'" onclick="getphotodetail(this.id,false);"><img  id="img'+photoitem[0]+'" class="currentview"  style="cursor:pointer;" src="'+staticpath+'/asset/photo/30x30/'+getPhotoPath(useridtmp)+'/'+photoitem[1]+ '" alt="'+photoitem[0]+'"/></a>';
							photoidtmp = photoitem[0];
							photofilename = photoitem[1];

                            groupInfoList = {};
                            if(ismypage2){
                                $("info").select("p[class='example']").each(function(element){
                                    element.style.display = "block";
                                });
                            }else{
                                $("info").select("p[class='example']").each(function(element){
                                    element.style.display = "none";
                                });
                            }
                            if(result.grouplist.length == 0)
                                hideElement("groupContainer");
                            else{
                                showElement("groupContainer");
                                hideElement("grouplist");

                                var grouplistitem = $("grouplistitem");
                                grouplistitem.innerHTML = "";

                                var groupphoto = $("groupphoto");
                                isMyPage_Group = ismypage2;
                                if(ismypage2){
                                    groupphoto.onclick = function(){showSaveGroupPhoto();}
                                    groupphoto.onmouseover = function(){groupphoto.style.backgroundColor = "#FFFF99";}
                                    groupphoto.onmouseout = function(){
                                        groupphoto.style.backgroundColor = "";
                                        new Effect.Highlight(groupphoto,{startcolor: "#FFFF99", endcolor: "", restorecolor: "", keepBackgroundImage: true});
                                    }

                                    var ul = document.createElement("ul");
                                    for(var id = 0; id < result.grouplist.length; id++){
                                        var groupInfo = result.grouplist[id];
                                        var li = document.createElement("li");
                                        var imgl = document.createElement("img");
                                        imgl.src = "/asset/group/"+groupInfo.displayPicture;
                                        imgl.className = "avatar avatar28";
                                        var span = document.createElement("span");
                                        span.innerHTML = groupInfo.groupName + " ";
                                        var input = document.createElement("input");
                                        input.type = "checkbox";
                                        input.checked = groupInfo.checked;
                                        input.value = groupInfo.id+":"+groupInfo.type;
                                        groupInfoList[groupInfo.id+":"+groupInfo.type] = groupInfo;

                                        li.appendChild(imgl);
                                        li.appendChild(span);
                                        li.appendChild(input);
                                        ul.appendChild(li);
                                    }
                                    grouplistitem.appendChild(ul);
                                }else{
                                    groupphoto.onclick = function(){}
                                    groupphoto.style.backgroundColor = "";
                                    groupphoto.onmouseover = function(){}
                                    groupphoto.onmouseout = function(){}
                                    for(var id = 0; id < result.grouplist.length; id++){
                                        var groupInfo = result.grouplist[id];
                                        groupInfoList[groupInfo.id+":"+groupInfo.type] = groupInfo;
                                    }
                                }
                                genGroupNameText();
                            }
                            
                            if(result.bloglist.length == 0)
                                hideElement('blogs');
                            else{
                                showElement('blogs');

                                var blogsinnerbody = $("blogsinnerbody");
                                if(blogsinnerbody){
                                    blogsinnerbody.innerHTML = "";

                                    var ul = document.createElement("ul");
                                    for(var blogid = 0; blogid < result.bloglist.length; blogid++){
                                        var li = document.createElement("li");
                                        var a = document.createElement("a");
                                        a.href = '/blog/view/'+result.bloglist[blogid][0];
                                        if(result.bloglist[blogid][1].length > 0){
                                            a.innerHTML = result.bloglist[blogid][1];
                                        }else{
                                            a.innerHTML = _("No blog title");
                                        }
                                        li.appendChild(a);
                                        ul.appendChild(li);
                                    }
                                    blogsinnerbody.appendChild(ul);
                                }
                            }
						}
					}
				}
				output += '<div class="clear"></div>';
				$('itemlist45').innerHTML = output;

				if (!firsttime)
				{
					var imgsrc = staticpath+'/asset/photo/medium/'+getPhotoPath(useridtmp)+'/'+ photofilename;
					
					setCropAvatar(imgsrc);
					
					imgdeleting = false;
	

					var currentOpacity = $('imageview').getOpacity() || 0.0;
					if(currentOpacity > 0) fadeDown(0.0);
					window.location.hash=photoidtmp;
					var img = new Image();
					img.onload = function(){
						if(fading) fading.cancel();
						var imageview = $('imageview');

						if (imageview.tagName=="CANVAS")
						{
							 var imgv = document.createElement('img');
							 imgv.alt = imageview.alt;
							 imgv.onclick = function(){openRawPopUpWindows();};
							 imgv.id = imageview.id
							 imgv.src = imageview.src;
							 imageview.parentNode.replaceChild(imgv, imageview);
							 imageview = $('imageview');
						}
						imageview.setOpacity(0);
						imageview.src=this.src;
						if(islandscape)
							islandscape=undefined;

						fadeUp(0.0);
						this.onload = function(){};
					}
					
					img.src = imgsrc;
					$('embledcode').value = "<a href='http://www.pg.in.th/photo/view/"+photoidtmp+"'><img src='"+img.src+"' alt='playground'/></a>";

					showcomments(photoidtmp,'0');

					getphotodetail2(result);
					if(!isLoadGMap)
					{
						loadGMap();
						isLoadGMap = true;
					}
				}
			},
			onFailure: function(t) {
				imgdeleting = false;
			}
		  }
	new Ajax.Request('/photo/detail/read/'+photoid, opt);
}

function saveGroupPhoto(){
    $("groupphoto").innerHTML = "Saving...";

    var groupidlist = new Array();
    $("grouplistitem").select("input").each(function(element){
        if(element.checked){
            var key = element.value.split(":");
            groupidlist.push([key[0],key[1]]);
        }
    });
    var opt = {
        postBody: "id="+photoidtmp+"&groupidlist="+groupidlist.toJSON(),
        onSuccess: function(t) {
            if(t.responseText == "200"){
                hideElement('grouplist');
                for(key in groupInfoList)
                    groupInfoList[key].checked = false;

                for(var i = 0; i<groupidlist.length; i++)
                    groupInfoList[groupidlist[i][0]+":"+groupidlist[i][1]].checked = true;

                genGroupNameText();
            }
			else
                cancelSaveGroupPhoto();
        },
        onFailure: function(t) {
            cancelSaveGroupPhoto();
        }
    }
    new Ajax.Request("/photo/saveGroupPhoto", opt);
}

function showSaveGroupPhoto(){
    $("grouplistitem").select("input").each(function(element){
        element.checked = groupInfoList[element.value].checked;
    })
    showElement('grouplist');
}

function cancelSaveGroupPhoto(){
    hideElement('grouplist');
}

function genGroupNameText(){
    var tmpGroupName = "";
    for(key in groupInfoList)
	{
        if(groupInfoList[key].checked)
			tmpGroupName += groupInfoList[key].groupName+ ", ";
	}
    if(tmpGroupName.length == 0){
        if(isMyPage_Group)
            tmpGroupName = _("Click here to add photo to your groups");
        else
            tmpGroupName = "";
    }
	else
        tmpGroupName = tmpGroupName.substring(0,tmpGroupName.length-2);

    $("groupphoto").innerHTML = tmpGroupName;
}

// set crop avatar
function setCropAvatar(src){
	var imgCrop = $('testImage');
    imgCrop.src = src;
    imgCrop.onload = function(){
        $("testWrap").appendChild($("testImage"));
        isInitCropper = undefined;
        $("testWrap").select("div[class='imgCrop_wrap']").each(function(element){
            element.parentNode.removeChild(element);
        });
    };
}


function fadeDown(start){
	if(fading) fading.cancel();
	var options = Object.extend({
		from: $('imageview').getOpacity() || 1.0,
		to: start,
		duration:0.3
	});
	fading = new Effect.Opacity($('imageview'),options);
}

function fadeUp(start){
	if(fading) fading.cancel();
	var options = Object.extend({
		from: ($('imageview').getStyle('display') == 'none' ? start : $('imageview').getOpacity() || start),
		to:   1.0,
		afterFinishInternal: function(effect) {
			effect.element.forceRerendering();
			hideElement('loading');
		},
		beforeSetup: function(effect) {
			effect.element.forceRerendering();
			effect.element.setOpacity(effect.options.from);
			effect.element.style.visibility = 'visible';
		},
		duration:0.3
	});
	fading = new Effect.Opacity($('imageview'),options);
}

function openRawPopUpWindows()
{
	var rawwindows = window.open('/photo/viewphoto/'+photoidtmp+'/raw','Playground','menubar=0,resizable=1,scrollbars=auto,status=0,toolbar=0,location=0');
}

//function getphotodetail(photoid)
//{
//	var randomnumber=Math.floor(Math.random()*9999999).toString()
//	var d = loadJSONDoc('/photo/GetPhotoDetail',{photoid:photoid,n:randomnumber});
//	d.addCallback(handleLoadCallback);
//}

function destroyEditInPlace()
{
	if (TitleEditor)
	{
		TitleEditor.destroy();
		TitleEditor = null;
	}
	/*if (TagsEditor)
	{
		TagsEditor.destroy();
		TagsEditor = null;
	}*/
	if (DescriptionEditor)
	{
		DescriptionEditor.destroy();
		DescriptionEditor = null;
	}
}
function loadMiniProfile(userid)
{
	var opt = {
		method: 'post',
		postBody: 'userid=' + userid,
		onSuccess: function(t) {
			$('miniprofile').innerHTML = t.responseText;
				$('asendPmMessage').onclick= function()
				{
						var opt = {
						method: 'post',
						postBody: "targetid="+userid+"&topic="+encodeURIComponent($('SendPmMessageTopic').value)+"&message="+encodeURIComponent($('PmMessage').value),
						onSuccess: function(t) {
							hideElement('sendpmmessage');
							$('messagealert').innerHTML = _('Send message completed');
							$('messagealert').style.display = 'block';
							setTimeout(function(){Effect.Fade('messagealert');},2000);
							//showElement('infobox');
							//$('infobox').focus();	
						},
						onFailure: function(t) {
							$('messagealert').innerHTML = _('Cannot send message');
							$('messagealert').style.display = 'block';
							setTimeout(function(){Effect.Fade('messagealert');},2000);
							//showElement('infobox');
							//$('infobox').focus();
						}
					  }
				new Ajax.Request('/sendPrivateMessage', opt);
				}
		},
			onFailure: function(t) {
			}
		}
	new Ajax.Request('/photo/miniprofile', opt);
}
function loadTagCloud(userid)
{
	var opt = {
	method: 'post',
	postBody: 'userid=' + userid,
	onSuccess: function(t) {
		$('tagcloud').innerHTML = t.responseText;
	},
		onFailure: function(t) {
		}
	}
	new Ajax.Request('/photo/widgetTagCloud', opt);
}
function getphotodetail2(result)
{
	if(window.location.href.indexOf('link#')>-1)
		document.title = result.titlePage.replace(/&#39;/g,"'");

    rotating = false;

	useridtmp = result.UserID
	
	if($('miniprofile'))
	{
		if($('miniprofile').innerHTML=='')
			loadMiniProfile(useridtmp);
	}

	if($('tagcloud'))
	{
		if($('tagcloud').innerHTML=='')
			loadTagCloud(useridtmp);
	}

	if($("shopInput"))
	{
		if (result.CanNotShow||result.IsDeleted)
			hideElement("shopInput");
		else
		{
			$("shopInput").className = "";
			$("shopInput").value = result.shopname;	
		}
	}

	hasBlog = result.hasBlog;
	blogUpdate = result.blogUpdate;

	var ismypage2 = result.isMyPage;
	updateLinkMenu(useridtmp);
	showElement('rotate90');
	showElement('rotate270');
	if (ismypage2)
	{
		$('rotate90').onclick = function(){rotateimage('90');};
		$('rotate270').onclick = function(){rotateimage('270');};
		ismypagetmp = true;
		showElement('deleteimg');
		showElement('setavatarbutton');
		hideElement('sendimproper');
		EditInPlace();
	}
	else
	{
		$('rotate90').onclick = function(){rotate('imageview',-90);};
		$('rotate270').onclick = function(){rotate('imageview',90);};
		destroyEditInPlace();
		hideElement('deleteimg');
		hideElement('setavatarbutton');
		ismypagetmp = false;

		if(result.showSendImproper)
			showElement("sendimproper");
		else
			hideElement("sendimproper");
	}
	
	hideElement("star");
	hideElement("stared");
	if(result.showStar)
	{
		if (result.isStarred)
		{
			hideElement("star");
			showElement("stared");
		}
		else
		{
			showElement("star");
			hideElement("stared");
		}
	}
	else
	{
			hideElement("star");
			hideElement("stared");
	}
	
	phototitle = Trim(result.Title);
	if (Trim(result.Title) == '' && ismypage2)
	{
		$('Title').innerHTML = _("Click here for edit title");
		$('imageview').alt = "";
	}
	else
	{
		if (Trim(result.Title) == '')
		{
			$('Title').innerHTML = "&nbsp;";
			$('imageview').alt = "";
		}
		else
		{
			$('Title').innerHTML = result.Title;
			$('imageview').alt = descapeSpecialHtmlCharacter(result.Title);
		}
	}
	
	$("facebook_like_button").src = "http://www.facebook.com/plugins/like.php?href=http%253A%252F%252Fwww.pg.in.th%252Fphoto%252Fview%252F"+ photoidtmp +"&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;font&amp;colorscheme=light&amp;height=35";
	//$("emailMessage").value = "[Playground] " + result.Title + " - http://www.pg.in.th/p/" + photoidtmp;

	if (Trim(result.Description) == '' && ismypage2)
		$('Description').innerHTML = _("Click here to edit detail");
	else
		$('Description').innerHTML = result.Description;

	if (Trim(result.PhotoTags) == '' && ismypage2){
		$('Tags').innerHTML = _("Click here to edit tags");
		$('tagsInput').value = '';
	}
	else
	{
		$('Tags').innerHTML = result.PhotoTags;
		$('tagsInput').value = result.PhotoTagsDescape;
	}
	
	var phototags = $("Tags");
	if(ismypage2){
		phototags.onclick = function(){showElement("edittags");hideElement("Tags");}
        phototags.onmouseover = function(){phototags.style.backgroundColor = "#FFFF99";}
        phototags.onmouseout = function(){
				phototags.style.backgroundColor = "";
				new Effect.Highlight(phototags,{startcolor: "#FFFF99", endcolor: "", restorecolor: "", keepBackgroundImage: true});
        }
	}else{
		phototags.onclick = function(){}
        phototags.style.backgroundColor = "";
        phototags.onmouseover = function(){}
        phototags.onmouseout = function(){}
	
	}

	if($('hprevious'))
	{
		$('hprevious').value = result.Previous;
		if (result.Previous == '#')
			hideElement('previous');
		else
			showElement('previous');
	}

	if($('hnext'))
	{
		$('hnext').value = result.Next;
		if (result.Next == '#')
			hideElement('next');
		else
			showElement('next');
	}

	hideElement('mobiledetail');
	if (result.DeviceImage != '')
	{
		showElement('mobiledetail');
		$('mobileimg').src="/device/"+result.DeviceImage;
		$('mobilename').innerHTML = result.DeviceBrand + " " + result.DeviceModel;
		mobileurl = result.DeviceURL;
		if (mobileurl != '')
			$('mobileimg').style.cursor = 'pointer';
		else
			$('mobileimg').style.cursor = '';
	}
	
	if (result.Channel != "") {
		var channel = ""
		if (result.Channel == 'MMS' || result.Channel == 'Share Online' || result.Channel == 'SmartChat') 
			channel = result.Channel;
			
		if (result.Channel=='PG Client - Gallery')
			channel = 'Gallery';
			
		if (channel!="")
		{
			$('Channel').innerHTML = channel;
			showElement('p_channel');
		}
		else
		{
			$('Channel').innerHTML = "&nbsp;";
			hideElement('p_channel');
		}
	}
	else
	{
		$('Channel').innerHTML = "&nbsp;";
		hideElement('p_channel');
	}
		
	if (result.UploadDate == "")
		$('UploadDate').innerHTML = "&nbsp;";
	else
		$('UploadDate').innerHTML = result.UploadDate;

	if (result.MobileCellLocation == '') 
		$('Location').innerHTML = "&nbsp;";
	else
		$('Location').innerHTML = result.MobileCellLocation;


	if (result.VisitorCount == '')
		$('VisitorCount').innerHTML = '0';
	else
		$('VisitorCount').innerHTML = result.VisitorCount;

	$('useravatar').title = result.UserDisplayName;

	$('photoprivacy').className = result.photoprivacy+"-item";
	$('privacy').innerHTML = result.privacylist[result.photoprivacy];

	if (result.photoprivacy!='improper')
	{
		//if(PhotoPrivacy==null)
		//	PhotoPrivacy = CreateInPlaceCollection();
		//PhotoPrivacy.options.value = result.photoprivacy;
		//PhotoPrivacy.url = "/photo/setphotoprivacy?pid=" + result.PhotoID;
	}
	else
	{
		//PhotoPrivacy.destroy();
		//PhotoPrivacy = null;
		$('privacy').innerHTML = _("Improper");
	}

	if (result.Location == ''){
		hideElement('map_container');
		hideElement('photomap-embedcode');
        hideElement('quickpost-googlemapembed');
		$('viewlargemap').onclick= function(){};
		hideElement('viewlargemap');
		if(ismypagetmp){
			showElement('mapeditbtn');
			$("mapeditbtn").innerHTML = _('Add Location');
		}else{
			hideElement('mapeditbtn');
		}
		if ($("addshopbtn"))
			showElement("addshopbtn");
	}else
	{
		showElement('map_container');
		showElement('photomap-embedcode');
        $('quickpost-googlemapembed').style.display = 'inline';
		if(ismypagetmp){
			showElement('mapeditbtn');
			$("mapeditbtn").innerHTML = _('Edit Location');
		}else{
			hideElement('mapeditbtn');
		}

		locationlist = result.Location.split(',');
		if ($("addshopbtn"))
		{
			$("addshopbtn").href = "/shop?@="+locationlist[0]+','+locationlist[1];
			showElement("addshopbtn");
		}

		$('viewlargemap').onclick= function(){window.open('http://maps.google.com/?q=@'+locationlist[0]+','+locationlist[1]+'&z=13');};
		showElement('viewlargemap');
		waitForGoogle();
		//if (GBrowserIsCompatible())
		//{
		//	if(marker) map.removeOverlay(marker);

		//	defaultPoint = new GLatLng(Number(locationlist[0]),Number(locationlist[1]));
	    //    point = defaultPoint;
		//	marker = new GMarker(point);
		//	map.setCenter(point, Number(locationlist[2]));
		//	map.addOverlay(marker);
			//if(isEditableMode == true) cancelEditableMode();
		//}
	}
}

function EditInPlace()
{
	TitleEditor.url = '/photo/edit/'+photoidtmp+'/title';
	DescriptionEditor.url ='/photo/edit/'+photoidtmp+'/description';
}

function showcomments(photoid,commentspage)
{
	var opt = {
			method: 'get',
			onSuccess: function(t) {
				if(t.responseText.indexOf('commentitem')!=-1  || commentpageno == 0)
				{
					hideElement('commentloading');
					commentposting = false;
					commentpageno = commentspage;
					$('commentlist').innerHTML = t.responseText;
				}
				else
				{
					commentpageno = (parseInt(commentspage)-1).toString();
					showcomments(photoid,commentpageno);
				}
				ReplacePgLinkComment();
			},
			onFailure: function(t) {
				hideElement('commentloading');
				commentposting = false;
				$('commentlist').innerHTML = t.responseText;
			}
		  }
	new Ajax.Request('/photo/comment/read/'+photoid+'/'+commentspage, opt);
}

function commentsubmit()
{
	if(commentposting)
	{
		alert(_('Posting comment. Please wait'));
		return;
	}

	if(Trim($('txtcomment').value)=='')
		return;
	showElement('commentloading');
	commentposting = true;
    var posttext = encodeURIComponent($('txtcomment').value);
	var opt = {
			method: 'post',
			postBody: 'photoid=' + photoidtmp + '&userid=' + owneridtmp + '&text=' + posttext,
			onSuccess: function(t) {
				showcomments(photoidtmp,'0')
				$('txtcomment').value="";
				showrecentupdate(useridtmp);
			},
			onFailure: function(t) {
				hideElement('commentloading');
				commentposting = false;
				$('showcomments').innerHTML = t.responseText;
			}
		  }
	new Ajax.Request('/photo/PostPhotoComment', opt);
}

function quotesubmit(qid,types,itemid,commentid)
{
	if(commentposting)
	{
		alert(_('Posting comment. Please wait'));
		return;
	}
	if(Trim($(qid).value)=='')
		return;
	showElement('loading'+qid.substring(4));
	commentposting = true;
    var posttext = encodeURIComponent($(qid).value);
	var opt = {
			method: 'post',
			postBody: 'photoid=' + photoidtmp + '&userid=' + owneridtmp + '&text=' + posttext + "&commentid=" + commentid,
			onSuccess: function(t) {
				showcomments(photoidtmp,'0')
				$(qid).value="";
				showrecentupdate(useridtmp);
			},
			onFailure: function(t) {
				commentposting = false;
				hideElement('loading'+qid.substring(4));
				$('showcomments').innerHTML = t.responseText;
			}
		  }
	new Ajax.Request('/photo/PostPhotoComment', opt);
}

function replysubmit(rid,types,itemid,commentid)
{
	if(commentposting)
	{
		alert(_('Posting comment. Please wait'));
		return;
	}
	if(Trim($(rid).value)=='')
		return;
	showElement('replyloading'+rid.substring(4));
	commentposting = true;
    var posttext = encodeURIComponent($(rid).value);
	var opt = {
			method: 'post',
			postBody: 'photoid=' + photoidtmp + '&userid=' + owneridtmp + '&text=' + posttext + "&commentid=" + commentid +"&isreply=True",
			onSuccess: function(t) {
				showcomments(photoidtmp,'0')
				$(rid).value="";
				showrecentupdate(useridtmp);
			},
			onFailure: function(t) {
				commentposting = false;
				hideElement('replyloading'+rid.substring(4));
				$('showcomments').innerHTML = t.responseText;
			}
		  }
	new Ajax.Request('/photo/PostPhotoComment', opt);
}

var quickPostIndexPage;

function quickPostIndex(){
	$('quickpost').innerHTML = quickPostIndexPage;
    $('quickpost-googlemapembed').style.display = ($('map_container').style.display == "block")?'inline':'none';
}

var preloadimg = new Image();
preloadimg.src="/static/v2p/images/share-loader.gif";

function socialnetworkLoginPage(network){
	if(network == "twitter"){
		sharecount(network,'clicked');
		url = "http://twitter.com/home?status=[Playground] " + encodeURIComponent(phototitle) + " - http://www.pg.in.th/p/" + photoidtmp;
		window.open(url);
		return;
	}
	if(network=="email"){
		showElement("shareemail");
		return;
	}
	if(!quickPostIndexPage) quickPostIndexPage = $('quickpost').innerHTML;

	showElement('qppostingimg');
	sharecount(network,'clicked');
    hideElement("quickpost")

	var opt = {
        onSuccess: function(result){
            if(result.responseText == 401){
                showElement("addNewNetworkBtn");
                $("infotext").innerHTML = _("incorrect email or password");
                showElement("infobox");
            }else{
                $('quickpost').update(result.responseText);
                hideElement('qppostingimg');
                showElement("quickpost");
            }
        },
        onFailure: function(result){
            $("infotext").innerHTML = _('Cannot show %s login page').replace("%s",network);
            showElement("infobox");
            hideElement('qppostingimg');
            showElement("quickpost");
        },
        onTimeout: onTimeout
    }
	new Ajax.Request('/socialnetwork/login/'+network, opt);
}
function selectAlbumList(){
    var selectList = $("select"+$("email").value);
    if(selectList!=null){
        $("albumId").replace('<select id="albumId">'+selectList.innerHTML+'</select>');
        $("socialnetworkPostBtn").style.display = "block"
    }else{
        $("albumId").replace('<span id="albumId">'+_("You don't have any album.")+'</span>');
        $("socialnetworkPostBtn").style.display = "none";
    }
}

function refreshAlbumList(form,network){
	if(!quickPostIndexPage) quickPostIndexPage = $('quickpost').innerHTML;

	var valid = false;
	if(form.email.value == ""){
		$("infotext").innerHTML = _('Please enter email address');
		showElement("infobox");
		return;
	}else if(form.password.value == "")
		$("infotext").innerHTML = _('Please enter password');
	else
		valid = true;

	if(!valid)
	{
		showElement("infobox");
		return;
	}

	$("refreshAlbumBtn").innerHTML = "<img src='/static/v2p/images/share-loader.gif' style='width: 16px; height: 16px;'/>";

	var opt = {
				postBody: 'refreshAlbumList=&email='+form.email.value+ '&password='+form.password.value +'&network='+network,
				onSuccess: function(t){
					if(t.responseText == 201){
						$("refreshAlbumBtn").innerHTML = _('update');
						socialnetworkLoginPage(network);
					}else if(t.responseText == 401){
						$("infotext").innerHTML = _('Invalid username or password');
						showElement("infobox");
						$("refreshAlbumBtn").innerHTML = _('update');
					}else{
						$("infotext").innerHTML = _('Cannot update album');
						showElement("infobox");
						$("refreshAlbumBtn").innerHTML = _('update');
					}
				},
				onFailure: function(t){
					$("infotext").innerHTML = _('Cannot update album');
					showElement("infobox");
					$("refreshAlbumBtn").innerHTML = _('update');
				},
				onTimeout: onTimeout
			}
	new Ajax.Request('/socialnetwork/login', opt);
}
function socialnetworkLogin(form,network){
	if(!quickPostIndexPage) quickPostIndexPage = $('quickpost').innerHTML;
	
	var valid = false;
	if(form.email.value == "")
		$("infotext").innerHTML = _('Please enter email address');
	else if(network != 'multiply' && checkEmail(form.email.value) == false)
		$("infotext").innerHTML = _('incorrect email format');
	else if(form.password.value == "")
		$("infotext").innerHTML = _('Please enter password');
	else
		valid = true;

	if(!valid)
	{
		showElement("infobox");
		return;
	}

	$("refreshAlbumBtn").style.display = 'block';
	sharecount(network,'shared');
	var opt = {
				postBody: 'refreshAlbumList=&email='+form.email.value+ '&password='+form.password.value +'&network='+network,
				onSuccess: function(t){
					if(t.responseText == 201){
						$("refreshAlbumBtn").style.display = 'none';
						socialnetworkLoginPage(network);
					}else if(t.responseText == 401){
						$("infotext").innerHTML = _('Invalid username or password');
						showElement("infobox");
						$("refreshAlbumBtn").style.display = 'none';
					}else if(t.responseText == 501){
						$("infotext").innerHTML = _('The album cannot be updated');
						showElement("infobox");
						$("refreshAlbumBtn").style.display = 'none';
					}else if(Number(t.responseText)){
						$("infotext").innerHTML = _('Can not login');
						showElement("infobox");
						$("refreshAlbumBtn").style.display = 'none';
					}else{
						$('quickpost').update(t.responseText);
					}
				},
				onFailure: function(t){
					$("infotext").innerHTML = _('Can not login');
					showElement("infobox");
					$("refreshAlbumBtn").style.display = 'none';
				},
				onTimeout: onTimeout
			}
	new Ajax.Request('/socialnetwork/login', opt);
}
function switchToEmbedCode(){
	if(!quickPostIndexPage) quickPostIndexPage = $('quickpost').innerHTML;
    sharecount('embeded','clicked');
	$('quickpost').innerHTML =  '<div id="socialloginform"><a onclick="quickPostIndex()" class="deleteoverlay deleteicon" href="javascript:void(0);">'+_("Back")+'</a>'+
								'<h2 id="embedurl">Embeded URL</h2>'+
								'<p>'+
									'<input id="inputembed" type="text" onclick="this.focus();this.select();" value="'+$('embledcode').value+'"/>'+
								'</p>'+
								'<div class="clear"></div></div>';
	$('inputembed').select();
}
function checkEmail(email) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) return true;
	return false;
}
function postToAlbum(form,network){
	waiting();
    sharecount(network,'shared');
	var opt = {
				method: 'post',
				postBody: 'id='+photoidtmp+ '&email='+form.email.value+ '&password='+form.password.value+ '&albumId='+form.albumId.value+ '&network='+network,
				onSuccess: postResult,
				onFailure: postResult,
				onTimeout: onTimeout
			}
	new Ajax.Request('/socialnetwork/postToAlbum', opt);
}
function submitQuickpost(e,form,network){
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return;

	if (keycode == 13)
		socialnetworkLogin(document.quickpostlogin,network);
}
function waiting(){
	var options = {
		loadingImage: "/static/v2p/images/shadowbox_mac_loading.gif",
		listenOverlay: false,
		initialHeight: '32px',
		initialWidth: '32px',
        text:           {
            cancel:     '',
            loading:    '',
            close:      '',
            next:       '',
            prev:       '',
            errors:     {
                single: 'You must install the <a href="{0}">{1}</a> browser plugin to view this content.',
                shared: 'You must install both the <a href="{0}">{1}</a> and <a href="{2}">{3}</a> browser plugins to view this content.',
                either: 'You must install either the <a href="{0}">{1}</a> or the <a href="{2}">{3}</a> browser plugin to view this content.'
            }
        }
	};
	Shadowbox.init(options);
	Shadowbox.open({
        title:      '',
        type:       'html',
        content:    '<img src="/static/v2p/images/shadowbox_mac_loading.gif"/>',
        height:     '32px',
        width:      '32px'
    });
}
function postResult(result){
	$('quickpost').innerHTML = result.responseText;
	Shadowbox.close();
}
function onTimeout(){
	$('quickpost').innerHTML = '<p>_("There is no response from server. Please try again")<a href="javascript:quickPostIndex()">Back</a></p>'
	Shadowbox.close();
}

function submitenter(input,e){
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return;

	if (keycode == 13){
	   searchLocation();
	   input.focus();
	   input.select();
	}
}

function updateLocation(){
	hideElement("mapsearchbox");

	if(point == undefined) return;

	var opt = {
		parameters: {
			id: photoidtmp,
			Name: $("locationName").value,
			Latitude: point.lat(),
			Longtitude: point.lng(),
            Zoom: mapsearch.getZoom()
		},
		onSuccess: function(result) {
			$("mapeditbtn").innerHTML = _('Edit Location');

			if(marker){
				GEvent.clearListeners(marker, 'dragend');
				mapsearch.removeOverlay(marker);
				marker = undefined;
			}
			GEvent.clearListeners(mapsearch, 'click');
			
			defaultPoint = point;
			marker = new GMarker(point);
			map.addOverlay(marker);
			map.setCenter(point, mapsearch.getZoom());

			$("Location").innerHTML = $("locationName").value.escapeHTML();
			$("msgdiv").innerHTML = "";
			isEditableMode = false;
		},
		onFailure: function(t) {
			$("infotext").innerHTML = _('The location cannot be editted');
			showElement("infobox");
		}
	}
	new Ajax.Request("/"+page+"/updateLocation", opt);

	$("msgdiv").innerHTML = "";
	$("searchResultDiv").innerHTML = "";
}

function sendPM(id)
{
	var topic = $('topic'+id).value;
	var message = $('msg'+id).value;
	var targetid = $('huid'+id).value;
	var postdata = "userid=" + owneridtmp + "&targetid=" + targetid + "&topic="+ encodeURIComponent(topic) + "&message=" + encodeURIComponent(message);
	var posturl = "/sendPrivateMessage";
	hideElement('p'+id);
	var opt = {
			method: 'post',
			postBody: postdata,
			onSuccess: function(t) {
				$('topic'+id).value = "";
				$('msg'+id).value = "";
				if (t.responseText=="Success")
				{
					$('infotext').innerHTML = _('Send message completed');
					showElement('infobox');
					$('infobox').focus();
				}
			},
			onFailure: function(t) {
				$('topic'+id).value = "";
				$('msg'+id).value = "";
				$('infotext').innerHTML = _("Cannot send message");
				showElement('infobox');
				$('infobox').focus();
			}
		  }
	new Ajax.Request(posturl, opt);
}

function starredPhoto()
{
		if(photoidtmp!='')
		{
				var opt = {
					method: 'post',
					postBody: 'id=' + photoidtmp,
					onSuccess: function(t) {
						hideElement("star");
						showElement("stared");
					},
					onFailure: function(t) {
					}
				}
				new Ajax.Request('/photo/starred', opt);
		}
}

function clearStarredPhoto()
{
		if(photoidtmp!='')
		{
				var opt = {
					method: 'post',
					postBody: 'id=' + photoidtmp,
					onSuccess: function(t) {
						showElement("star");
						hideElement("stared");
					},
					onFailure: function(t) {
					}
				}
				new Ajax.Request('/photo/clearstarred', opt);
		}
}

// Execute Ajax
/*collection = "";
function getQueryTags(userInput, standalone){
		var opt = {
				method: 'post',
				postBody: 'subString=' + encodeURIComponent(userInput.charAt(0)),
				onSuccess: function(t) {
					searchResults = t.responseText.evalJSON();
					//collection = searchResults.tagslist;
					if(obj_collection=t.responseText){
						if(siw){
							datasrcname = collection;
						}
						eval(datasrcname+'='+obj_collection+';');
						runMatchingLogic(userInput, standalone);
					}
				},
				onFailure: function(t) {}
			}
		new Ajax.Request('/photo/getQueryTags', opt);
}*/

//sendImproper
function sendImproper(){
		var opt = {
				method: 'post',
				postBody: 'id=' + photoidtmp ,
				onSuccess: function(t) {
					if (t.responseText=="Improper"){
						$('infotext').innerHTML = _("This photo has been set to improper");
					}
					else if (t.responseText=="OK"){
						$('infotext').innerHTML = _("This photo has been reported as improper");
					}
					else if (t.responseText=="Repeatedly"){
						$('infotext').innerHTML = _("You have already reported this photo as improper");
					}
					else if (t.responseText=="False"){
						$('infotext').innerHTML = _("You have already reported this photo as improper");
					}
					else {
					}
					showElement('infobox');
					$('infobox').focus();
				},
				onFailure: function(t) {}
			}
		new Ajax.Request('/photo/setImproper', opt);
}

function waitForGoogle() 
{		counter++;
		if(timeoutId!=-1)
			window.clearTimeout(timeoutId);
		if(!isLoadGMap)
		{
			if(!map)
			{
				map = new GMap2($("map"));
				smallZoomControl = new GSmallZoomControl();
				map.addControl(smallZoomControl);
				if(map.checkResize)
				{
					if(isEditableMode)cancelEditableMode();

					map.checkResize();
					isLoadGMap = true;
				}
			}
		}

		if(isLoadGMap)
		{	
			if (GBrowserIsCompatible())
			{
				if(marker) map.removeOverlay(marker);

				defaultPoint = new GLatLng(Number(locationlist[0]),Number(locationlist[1]));
				point = defaultPoint;
				marker = new GMarker(point);
				map.setCenter(point, Number(locationlist[2]));
				map.addOverlay(marker);
				//if(isEditableMode == true) cancelEditableMode();
				counter = 0
				window.clearTimeout(timeoutId);
			}
			else
			{
				if(counter < 100)
					timeoutId = window.setTimeout(waitForGoogle, 100);
				else
				{
					counter = 0;
					window.clearTimeout(timeoutId);
				}
			}
		}
		else
		{
			if(counter < 100)
				timeoutId = window.setTimeout(waitForGoogle, 100);
			else
			{
				counter = 0;
				window.clearTimeout(timeoutId);
			}
		}
}

function saveTags(value){
		if(photoidtmp!='')
		{
				$("Tags").innerHTML = 'Save...'
				var opt = {
					method: 'post',
					postBody: 'value=' + encodeURIComponent(value),
					onSuccess: function(t) {
						if(t.responseText == ''){
							$("Tags").innerHTML = _('Click here to edit tags');
						}
						else{
							$("Tags").innerHTML =  t.responseText;
						}
					},
					onFailure: function(t) {
					}
				}
				new Ajax.Request('/photo/edit/'+ photoidtmp +'/tag', opt);
		}
}

var sendmailactive = false;
function shareSendMail(){
	tomail = $("SendEmailTo").value;
	subject = $("sendemailsubject").value;
	message = $("emailMessage").value;
	
	if(tomail == ''){
		return
	}
	if(subject == ''){
		return
	}
	if(message == ''){
		return
	}
	if(sendmailactive)
		return
	
	sendmailactive = true;
	var opt = {
		method: 'post',
		postBody: 'tomail=' + encodeURIComponent(tomail) + '&subject=' + encodeURIComponent(subject) + '&message=' + encodeURIComponent(message) + '&photoid=' + photoidtmp,
		onSuccess: function(t) {
			if(t.responseText == 'OK'){
				$("infotext").innerHTML = _('Send mail complete.');
			}
			else{
				$("infotext").innerHTML = _('Send mail Error.');
			}
			hideElement("shareemail")
			showElement("infobox");
			sendmailactive = false;
		},
		onFailure: function(t) { 
			sendmailactive = false;
		}
	}
	new Ajax.Request('/photo/shareMail', opt);
}
function sharecount(web,action){
	var validweb = "hi5,multiply,facebook,friendster,picasa,flickr,embeded,twitter";
	var validaction = "clicked,shared";
	if (web && action)
	{
			web = web.toLowerCase();
			action = action.toLowerCase();
			if (validweb.indexOf(web)==-1)
				return 
			if (validaction.indexOf(action)==-1)
				return
			var opt = {
				method: 'get',
				onSuccess: function(t) {},
				onFailure: function(t) {}
			}
			new Ajax.Request('/photo/countshare/'+web+'/'+action, opt);
	}
}
//]]>
