var slideShowID;
var formPostType='';
var picID='';
var formFid='';
var formAid='';
var formPid='';
var formPrevAid='';
var actAlbPg='';
var userAgent = navigator.userAgent.toLowerCase();
var enabletip = false;
var histEnabled=false;

//document.write("<" + "script src=\"\/js\/swfobject.js\"></" + "script>");

function showAlb(){
	$('#albBlock').show();
	$('#picBlock').hide();
}

function showComments(picid,cpage,gid,albumid,smileys,comtp,comord){
  	$.ajax({
		beforeSend:function(){$("#picComments").html('<img src="http://img.draugiem.lv/img/load.gif" />&nbsp;');},
		url:"/gal/com.php?pic="+picid+"&cpg="+cpage+'&fid='+gid+'&aid='+albumid+(smileys?'&smileys='+smileys:'')+(comtp?'&comtp='+comtp:'')+(comord?'&comord='+comord:'')+'&DS='+sessid,
		success: function(txt){$("#picComments").html(txt);},
		error:function(txt){$('#picComments').append("<li>kluda "+txt+"</li>");}
	});  
}

function writeToLayer(lay,txt){
  try{
    document.getElementById([lay]).innerHTML = txt;
  }catch(e){
    over = document.getElementById([lay]);
    range = document.createRange();
    range.setStartBefore(over);
    domfrag = range.createContextualFragment(txt);
    while (over.hasChildNodes()){
      over.removeChild(over.lastChild);
    }
    over.appendChild(domfrag); 
  }
}

function resizeDivs(){
  var agt = navigator.userAgent.toLowerCase();
  var ie=(agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1);
  document.body.scroll='no';
  document.body.style.overflow="hidden";
  var h=document.getElementById('popupHeader');
  var c=document.getElementById('popupCenter');
  var f=document.getElementById('popupFooter');
  if(h){hh=h.offsetHeight;}else{hh=0;}
  if(f){fh=f.offsetHeight;}else{fh=0;}
  c.style.overflow='auto';
  c.style.height=((ie?document.body.clientHeight:document.body.clientHeight-20)-(fh)-(hh))+'px';
  c.style.width=(ie?'100%':(document.body.clientWidth-20)+'px');
}

var selectedStars = 0;

function highlightStars(cnt){
    if (document.getElementById){
        unhighlightStars(true);
        for (i = 1; i <= cnt; i++){
            document.getElementById('video_rating_star_' + i).src="/img/star_on.gif";
        }
    }
}

function unhighlightStars(forced){
    if (document.getElementById){
        if (selectedStars == 0 || forced){
            for (i = 1; i <= 5; i++){
                document.getElementById('video_rating_star_' + i).src="/img/star_off.gif";
            }
        }else{
            highlightStars(selectedStars);
        }
    }
}

function selectStars(cnt){
    selectedStars = cnt;
    document.getElementById('videoRating').value=selectedStars;
}

var offsetxpoint;
var offsetypoint;
var ie;
var ns6;
var enabletip;
var tipobj;

function initDD(){
	if(!document.getElementById('drdhtmltooltip')){
		var div = document.createElement('div');
		div.id = 'drdhtmltooltip';
		document.body.appendChild(div);
	}
	offsetxpoint=-10; 
	offsetypoint=20;
	ie=document.all;
	ns6=document.getElementById && !document.all;
	enabletip=false;
	tipobj=document.getElementById("drdhtmltooltip");
}

function initAdm(){
	if(document.getElementById('sHead')){
		document.getElementById('adminBlock').style.display=(document.getElementById('adminBlock').style.display=='none'?'block':'none');
		document.getElementById('sHead').className=(document.getElementById('sHead').className=='hdr'?'hdrOn':'hdr');
	}
	if(document.getElementById('sHead2')){
		document.getElementById('adminBlock2').style.display=(document.getElementById('adminBlock2').style.display=='none'?'block':'none');
		document.getElementById('sHead2').className=(document.getElementById('sHead2').className=='hdr'?'hdrOn':'hdr');
	}
}

function ietruebody(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function ddrivetip(thetext, thecolor, thewidth){
try{
if (ns6||ie){
if (typeof thewidth!="undefined") tipobj.style.width=thewidth+"px"
if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor
tipobj.innerHTML=thetext
enabletip=true
return false
}
}catch(e){}
}

function positiontip(e){
try{
if (enabletip){
var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
//Find out how close the mouse is to the corner of the window
var rightedge=ie&&!window.opera? ietruebody().clientWidth-event.clientX-offsetxpoint : window.innerWidth-e.clientX-offsetxpoint-20
var bottomedge=ie&&!window.opera? ietruebody().clientHeight-event.clientY-offsetypoint : window.innerHeight-e.clientY-offsetypoint-20

var leftedge=(offsetxpoint<0)? offsetxpoint*(-1) : -1000

//if the horizontal distance isn't enough to accomodate the width of the context menu
if (rightedge<tipobj.offsetWidth)
//move the horizontal position of the menu to the left by it's width
tipobj.style.left=ie? ietruebody().scrollLeft+event.clientX-tipobj.offsetWidth+"px" : window.pageXOffset+e.clientX-tipobj.offsetWidth+"px"
else if (curX<leftedge)
tipobj.style.left="5px"
else
//position the horizontal position of the menu where the mouse is positioned
tipobj.style.left=curX+offsetxpoint+"px"

//same concept with the vertical position
if (bottomedge<tipobj.offsetHeight)
tipobj.style.top=ie? ietruebody().scrollTop+event.clientY-tipobj.offsetHeight-offsetypoint+"px" : window.pageYOffset+e.clientY-tipobj.offsetHeight-offsetypoint+"px"
else
tipobj.style.top=curY+offsetypoint+"px"
tipobj.style.visibility="visible"
}
}catch(e){}
}

function hideddrivetip(){
try{
if (ns6||ie){
enabletip=false
tipobj.style.visibility="hidden"
tipobj.style.left="-1000px"
tipobj.style.backgroundColor=''
tipobj.style.width=''
}
}catch(e){}
}

if (window.ActiveXObject){
	window.attachEvent('onload',initDD);
}else{
	window.addEventListener('load',initDD,false);
}
document.onmousemove=positiontip;

//################################## jaunā versija sākas šite ###################################

var dragsort=false;
var junkdrawer=false;
var targetDiv='cs2';
var swfUplObj;

Draugiem.Gallery = {
	version: '4.3.12',
	initord: '',
	lastRq: '',
	lastRqArr: new Array(),
	formCancel:false,
	defaults: {loading: '...',delcom: 'sure?',sTagAdd:'add',sTagCancel:'cancel',sTagHint:'',sTagEnable:'',sTagDisable:''},
	uplCnt:0,
	uplDoneCnt:0,
	loadTime:0,
	loadTime2:0,
	formOptions: false,
	selAlb:false,
	selPic:false,
	selFid:false,
	initialized:false,
	selectedStars:0,
	smileyList:'',
	swfObjects:new Array(),
	
	init: function(target){
		if(!target && this.initialized){
			return true;
		}
		if($((target?'#'+target+' ':'')+'link[rel=prefetch]').size()){
			var loadTime=new Date();
			var cnt=$((target?'#'+target+' ':'')+'link[rel=prefetch]').each(function(){window.setTimeout("tmp=new Image();tmp.src = '"+$(this).attr('href')+"';",0);}).size();
			var now=new Date();
			D.console.info(cnt+' image prefetch '+(target?'@'+target+' ':'')+((now-loadTime)/1000).toFixed(2)+"sec");	
		}
		if($((target?'#'+target+' ':'')+'[id=th]').size()){
			var loadTime=new Date();
			var cnt=$((target?'#'+target+' ':'')+'[id=th]').hover(function(){$(this).addClass("pichover");},function(){$(this).removeClass("pichover");}).size();
			var now=new Date();
			D.console.info(cnt+" hovers "+(target?'@'+target+' ':'')+((now-loadTime)/1000).toFixed(2)+"sec");			
		}
		if(!target){
			window.setTimeout(function(){$("#pload").html($("#loadprogress").html());},1000);
		}
		if(!target){
			this.initialized=true;
		}
	},
	
	rq: function(url, target, tp){
		if(typeof(tp)=='undefined'){tp='';}
		if(this.lastRqArr[target]!=url){
			$.ajax({
				beforeSend:function(){$("#pload").show();loadTime=new Date();},
				url:url+(url.indexOf('?')==-1?'?':'&')+'DS='+sessid,
				success: function(txt){
					loadTime2=new Date();
					if(target){
						if(skin>1 && target.substring(0,2)=='cs'){
							var pre='<div class="skinbxtitle"><div class="skinbxcorner"></div></div><div class="skinbxbg">';
							var post='</div><div class="skinbxfooter"><div class="skinbxcorner"></div></div>';
						}else{
							var pre='';
							var post='';
						}
						var tm1=new Date();
/* 						if(tp=='1' && $((target?'#'+target+' ':'')+'#picBlock').get(0)){
							$('#outermost').append('<div id="galHidReq"></div>');
							$('#galHidReq').hide().html(txt);
							$("#"+target+" #picPath").html($('#galHidReq #picBlock #picPath').html());
							$("#"+target+" #videoAdmBox").html($('#galHidReq #picBlock #videoAdmBox').html());
							$("#"+target+" #picAdmBox").html($('#galHidReq #picBlock #picAdmBox').html());
							$("#"+target+" #picBottBox").html($('#galHidReq #picBlock #picBottBox').html());
							$("#"+target+" #carouselTarget").attr('act',($('#galHidReq #picBlock #carouselTarget').attr('act')));
							$('#galHidReq').remove();
						}else{	  */
							$("#"+target).html(pre+txt+post);
							evalScriptHTML(txt);
/*  						}  */
						var tm2=new Date();
						D.console.info("html "+(target?'@'+target+' ':'')+((pre+txt+post).length/1024).toFixed(2)+"Kb "+((tm2-tm1)/1000).toFixed(2)+"sec");						
						Draugiem.Tools.loadSkin(target);
						Draugiem.Gallery.init(target);
						Draugiem.Forms.load(target);
						//Draugiem.History.load(target);
						Draugiem.Tooltip.load(target);
					
						if($.browser.msie && $.browser.version<7){
							$('#'+target).pngFix();
						}
						$(document).ready(function(){
							if($('#smileystarget',$("#"+target)).get(0)){
								if(!Draugiem.Gallery.smileyList){
									Draugiem.Tools.loadScript('/gal/show/smileylist.php?DS='+sessid,function(){
										$('#smileystarget').html(Draugiem.Gallery.smileyList);
										$('.emoticons2').bind('click',function(event){smileys.hideEmoticonPopup();});
									});
								}else{
									$('#smileystarget').html(Draugiem.Gallery.smileyList);
									$('.emoticons2').bind('click',function(event){smileys.hideEmoticonPopup();});
								}
							}
							var carTarget=$('#carouselTarget',$("#"+target));
							if(carTarget.get(0)){
								var xmlurl=$(carTarget).attr('xmlurl');
								var active=$(carTarget).attr('act');
								if(Draugiem.Gallery.swfObjects[xmlurl]){
									if($('#carouselTarget').html()){
										changepic(active);
									}else{
										Draugiem.Gallery.swfObjects[xmlurl].addVariable('actelement',active);
										Draugiem.Gallery.swfObjects[xmlurl].write('carouselTarget'); 
									}
								}else{
									Draugiem.Gallery.swfObjects[xmlurl] = new SWFObject('/gal/show/carousel.swf?xmlurl='+xmlurl,'carousel',700,80,'#ffffff');
									//Draugiem.Gallery.swfObjects[xmlurl].addParam('wmode','transparent');
									Draugiem.Gallery.swfObjects[xmlurl].addVariable('actelement',active);
									Draugiem.Gallery.swfObjects[xmlurl].write('carouselTarget'); 
								}
							}
						});
/* 						if(typeof(Draugiem.Tools.callback)!=undefined && Draugiem.Tools.callback){
							window.setTimeout(Draugiem.Tools.callback,100);
						}		
*/						
						$('#tooltip').hide();
						$('#chInfo').show();
					}
				},
				error:function(txt){$('#'+target).append("<li>kluda "+txt+"</li>");},
				complete: function(){
						$("#pload").hide();
						var now=new Date();
						D.console.info("ajax load time "+((now-loadTime)/1000)+"/"+((now-loadTime2)/1000)+"sec ("+url+'@'+target+")");
					}
			});
			this.lastRqArr[target]=url;
		}
	},
	
	f: function(uid,target){ //first page
		this.rq("/gal/show/firstpage.php"+(uid?"?fid="+uid:''),(target?target:targetDiv));
	},
	a: function(uid,aid,pg,tg){ // album
		if($('#'+targetDiv).css('display')=='none'){
			for(i=1;i<=6;i++){
				if($('#cs'+i).css('display')!='none'){
					targetDiv='cs'+i;
				}
			}
		}	
		this.rq("/gal/show/album.php?fid="+uid+"&aid="+aid+(pg?'&pg='+pg:'')+'&tager='+tg,targetDiv);
	},
	tg: function (uid, pg) {
		this.rq("/gal/show/tag_user.php?uid="+uid+"&page="+pg,targetDiv); 
	},
	p: function(uid,aid,picid,chapter,tg,freeparam){ // picture/video
		if(typeof(freeparam)=='undefined'){freeparam='';}
		if(typeof(tg)=='undefined'){tg='';}
		$(".overlayPrevLink img").blur();
		$(".overlayNextLink img").blur();
		taggedResetRectangle();
		if(typeof(chapter)=='undefined'){chapter='';}
		if($('#'+targetDiv).css('display')=='none'){
			for(i=1;i<=6;i++){
				if($('#cs'+i).css('display')!='none'){
					targetDiv='cs'+i;
				}
			}
		}			
		if(aid<=-100){ // video 
			this.rq("/video/alb.php?aid="+aid+"&pic="+picid,targetDiv,1);
		}else{
			if(targetDiv=='cs2' && $('#'+targetDiv).css('display')=='none'){
				$('#ds2').click();
			}		
			this.rq("/gal/show/album.php?fid="+uid+"&aid="+aid+"&pic="+picid+"&ch="+chapter+'&tager='+tg+'&'+freeparam,targetDiv,'1');
		}
		if($('#similar').get(0)){
			this.rq("/video/similar.php?pic="+picid,'similar');
		}
	},
	l: function(uid,pg,theme){ // album list @ first page
		this.rq("/gal/show/alblist.php?fid="+uid+(pg?'&pg='+pg:'')+(theme?'&theme='+theme:''),'usrAlb');
	},
	c: function(picid,cpage,uid,aid,cid){ //comments
		this.rq("/gal/show/comments.php?pic="+picid+"&cpg="+cpage+'&fid='+uid+'&aid='+aid+'&c='+cid,'picComments');
	},
	s: function(aid){ // album stats
		this.rq("/gal/show/albstats.php?aid="+aid,targetDiv);
	},
	v: function(picid){ // vote stats
		this.rq("/gal/show/votestats.php?pic="+picid,'voteStats');
	},
	k: function(what,uid,aid,picid,sel,tg){ // carousel
		window.setTimeout(function(){Draugiem.Gallery.rq("/gal/show/carousel.php?fid="+uid+"&aid="+aid+"&pic="+picid+"&sel="+sel+"&tager="+tg,'picCar');},300);
	},
	dc: function(picid,uid,aid,cpg,delcom){ // delete comment
		if(confirm(this.defaults.delcom)){
			$('#picComments #com'+delcom).addClass('info').slideUp('slow');
			this.rq("/gal/submit/pub.php?pic="+picid+"&fid="+uid+"&aid="+aid+"&cpg="+cpg+"&delcom="+delcom,'formResp');
		}
	},
	vf: function(act,picid,uid,aid){ // video favorites
		this.rq("/gal/submit/pub.php?pic="+picid+"&fid="+uid+"&aid="+aid+"&videofav="+act,'formResp');
	},
	co: function(picid,cpg,uid,aid,act){ // comments options
		this.rq("/gal/submit/pub.php?pic="+picid+"&fid="+uid+"&aid="+aid+"&comact="+act+"&cpg="+cpg,'formResp');
	},
	vl: function(st,f,s,picid,pg){ // video list
		this.rq("/video/layout/tab"+st+".php?pic="+picid+"&st="+st+"&f="+f+"&s="+s+"&pg="+pg,'cs'+st);
	},
	
	x: function(aid,pg,pic,fid){
		if(typeof(pg)=='undefined'){pg=1;}
		if(typeof(aid)=='undefined'){aid=0;}
		if(typeof(pic)=='undefined'){pic=0;}
		if(typeof(fid)=='undefined'){fid=0;}
		Draugiem.Gallery.selAlb=0;
		Draugiem.Gallery.selPic=0;
		if(aid){
			Draugiem.Gallery.selAlb=aid;
		}
		if(pic){
			Draugiem.Gallery.selPic=pic;
		}
		if(fid){
			Draugiem.Gallery.selFid=fid;
		}

		$.ajax({
		beforeSend:function(){$("#pload").show();},
		url:'/gal/admin/album.php?aid='+aid+'&pg='+pg+(aid?'&tp=1':'')+(pic?'&pic='+pic:'')+(fid?'&fid='+fid:'')+'&rnd='+Math.floor(Math.random()*100)+'&DS='+sessid,
		success: function(template){
			$("#"+targetDiv).html(template);
			if(!$('#mnContext').get(0)){
				$('<div class="contextMenu" id="mnContext"></div>')
					.hide()
					.append('<ul><li id="zoom"><img src="/img/plus.gif"> Zoom</li><li id="rtr"><img src="/img/g/rr.gif"> Rotate right</li><li id="rtl"><img src="/img/g/rl.gif"> Rotate left</li><li id="delete"><img src="/img/deny.gif"> Delete</li></ul>')
					.appendTo('body');
			}
			if(typeof(ToolMan)=='undefined'){  // pārbaude lai nelādētu vēlreiz
				Draugiem.Tools.dhtmlLoadScript("/js/drag/compl.js");
			}
			/* 			
			if(typeof($.fn.contextMenu)=='undefined'){
				Draugiem.Tools.dhtmlLoadScript("/js/jquery.contextmenu.js");
			}	
			*/			
			Draugiem.Gallery.checkDragJsLoad(targetDiv); // pārbaudam vai ir ielādējies drag'n'drop un pēc tam taisam inicializāciju
			//window.setTimeout('Draugiem.Gallery.checkContextMenu();',100); // pārbaudam vai ir ielādējies contex tmenu
			//Draugiem.Tools.loadSkin(targetDiv);	
			//Draugiem.History.load(targetDiv);
			Draugiem.Tooltip.load(targetDiv);
			Draugiem.Forms.load(targetDiv);
			$("#admnav li b[class=admbxh]").click(function(){Draugiem.Gallery.showAdmBox($(this).parent()[0]);});
			$("#"+targetDiv+" li[rel=dragpic]").click(function(event){Draugiem.Gallery.goadm(this,event);return false;}).bind('mousedown',function(event){$('#tooltip').hide();});
			$("#"+targetDiv+" #chall").click(function(event){Draugiem.Gallery.bxSelAll(event);});
			$("#admnav li b[class=admbxh]").hover(function(){$(this).addClass("abxh");},function(){$(this).removeClass("abxh");});
			$("noscript").hide();
			$('#chInfo').show();
			if(pic){
				$("#admnavbx9 a[rel=dragpic]").click(function(event){Draugiem.Gallery.goadm(this,event);return false;});
			}
		},
		error:function(txt){$("#"+targetDiv).append("<li>kluda "+txt+"</li>");},
		complete: function(){$("#pload").hide();}
		});	
		this.lastRq=aid+pg;
		this.lastRqArr=new Array();
	},
	bxSelAll: function(event){
		if(document.getElementById('chall').checked){
			$('#boxes li').addClass('sel');
		}else{
			$('#boxes li').removeClass('sel');
		}
		this.goadm(false,event);
	},
	goadm: function(el,event){
		if (!event) event = window.event;
		if(!document.getElementById('chall').checked){
			if(!event.ctrlKey && !event.metaKey){
				$('#boxes li').removeClass('sel');
				if(el){
					$('#boxes #'+el.id).addClass('sel');
				}
			}else{
				if($('#boxes #'+el.id).attr('class')=='box sel'){
					$('#boxes #'+el.id).removeClass('sel');
				}else{
					$('#boxes #'+el.id).addClass('sel');
				}
			}
		}

		var idscnt=$('#boxes li[class=box sel]').size();
		if($("#admnavbx9in")[0]){
			if(idscnt==1){
				$.ajax({
					beforeSend:function(){$("#pload").show();},
					url:'/gal/admin/pic.php?pic='+$('#boxes li[class=box sel]').attr('id')+'&DS='+sessid,
					success: function(txt){
						$("#admnavbx9in").html(txt);
						Draugiem.Gallery.showAdmBox($("#admnavbx9").get(0));
						Draugiem.Forms.load('admnavbx9');
						Draugiem.Tools.loadSkin('admnavbx9');
						$("#admnavbx9 a[rel=dragpic]").click(function(event){Draugiem.Gallery.goadm(this,event);return false;});
					},
					complete: function(){$("#pload").hide();}
				});
			}
			if(idscnt>1){
				var ids='';
				$('#boxes li[class=box sel]').each(function(){ids+=$(this).attr('id')+',';});
				$.ajax({
					beforeSend:function(){$("#pload").show();},
					url:'/gal/admin/pic.php?pics='+ids.substring(0,ids.length-1)+'&DS='+sessid,
					success: function(txt){
						$("#admnavbx9in").html(txt);
						Draugiem.Gallery.showAdmBox($("#admnavbx9").get(0));
						Draugiem.Forms.load('admnavbx9');
						Draugiem.Tools.loadSkin('admnavbx9');
						$("#admnavbx9 a[rel=dragpic]").click(function(event){Draugiem.Gallery.goadm(this,event);return false;});
					},
					complete: function(){$("#pload").hide();}
				});
			}
			if(idscnt==0){
				this.showAdmBox($("#admnavbx0").get(0));
			}
		}
	},
	
	gotoPub: function(){
		if(this.selAlb && this.selPic){
			this.p((this.selFid?this.selFid:id),this.selAlb,this.selPic);
		}else if(this.selAlb){
			this.a((this.selFid?this.selFid:id),this.selAlb,1);
		}else{
			this.f((this.selFid?this.selFid:id));
		}
	},
	
	picList: function(fid,aid){
		$.ajax({
			beforeSend:function(){$("#pload").show();},
			url:'/gal/admin/piclist.php?fid='+fid+'&aid='+aid+'&noupl=1&DS='+sessid,
			success: function(txt){
				$("#galOuter").html(txt);
				$("#galOuter li[rel=dragpic]").click(function(event){Draugiem.Gallery.goadm(this,event);return false;});
				$("#galOuter #chall").click(function(event){Draugiem.Gallery.bxSelAll(event);});
				Draugiem.Gallery.checkDragJsLoad("galOuter"); 
				Draugiem.Tools.loadSkin("#galOuter");	
				//Draugiem.History.load("#galOuter"); 
				//Draugiem.Tooltip.load("galOuter");		
				$("noscript").hide();
				$("#chInfo").show();
			},
			complete: function(){$("#pload").hide();}
		});		
	},
	
	picListSingle: function(fid,aid,target){
		if(typeof(target)!='undefined'){
			var trg=target;
		}else{
			var trg='galOuter';
		}	
		$.ajax({
			beforeSend:function(){$("#pload").show();},
			url:'/gal/admin/piclist.php?fid='+fid+'&aid='+aid+'&noupl=1&DS='+sessid,
			success: function(txt){
				$("#"+trg).html(txt);
				$("#"+trg+" li[rel=dragpic]").click(function(event){Draugiem.Gallery.goadm(this,event);return false;});
				$("noscript").hide();
				$("#chInfo").hide();
			},
			complete: function(){$("#pload").hide();}
		});		
	},
	
	// Album foto editor - Svens
	picListFoto: function(fid,aid,target){
		if(typeof(target)!='undefined'){
			var trg=target;
		}else{
			var trg='galOuter';
		}
		$.ajax({
			beforeSend:function(){$("#pload").show();},
			url:'/foto/rq/piclistfoto.php?fid='+fid+'&aid='+aid+'&DS='+sessid,
			success: function(txt){
				$("#"+trg).html(txt);
				$("#"+trg+" li[rel=dragpic]").click(function(event){Draugiem.Gallery.goadm(this,event);return false;});
				//$("#galOuter #chall").click(function(event){Draugiem.Gallery.bxSelAll(event);});
				//Draugiem.Gallery.checkDragJsLoad("galOuter");
				//Draugiem.Tools.loadSkin("#galOuter");	
				//Draugiem.History.load("#galOuter");
				Draugiem.Tooltip.load("#"+trg);		
				$("noscript").hide();
				$("#chInfo").show();
			},
			complete: function(){$("#pload").hide();}
		});		
	},
	
	showAdmBox: function(ch){
		var state=$("#"+ch.id+" > "+"#"+ch.id+"in").css("display");
		if(ch.id!="admnavbx9" && $("#admnavbx9").css("display")!='none'){
			$("#admnavbx9").slideUp("fast");
		}
		for(i=0;i<=5;i++){
			if($("#admnavbx"+i+" > "+"#admnavbx"+i+"in").css("display")!='none'){
				$("#admnavbx"+i+"> "+"#admnavbx"+i+"in").slideUp("fast");
				$("#admnavbx"+i).removeClass("info");
				$("#admnavbx"+i).addClass("info_dark");				
			}
		}
		if(state=='none'){
			$("#"+ch.id+" > "+"#"+ch.id+"in").slideDown("fast");
			$("#"+ch.id).removeClass("info_dark");
			$("#"+ch.id).addClass("info");
		}
		if(ch.id=="admnavbx9" && $("#admnavbx9").css("display")=='none'){
			$("#admnavbx9").slideDown("fast");
		}
	},

	saveOrder: function(item){
		var group = item.toolManDragGroup
		var list = group.element.parentNode
		var id = list.getAttribute("id")
		if (id == null) return
		group.register('dragend', function(){
			drg=junkdrawer.serializeList(document.getElementById("boxes"));
			if(drg!=Draugiem.Gallery.initord){
				Draugiem.Gallery.initord=drg;
				D.console.info('save drag\'n\'drop results');
				$.ajax({
					beforeSend:function(){$("#pload").show();Draugiem.Gallery.info();},
					url:'/gal/submit/pic.php?drag='+drg+'&DS='+sessid,
					success: function(txt){
						D.console.info('drag success');
						$('#formResp').html(txt);
					},
					complete: function(){$("#pload").hide();InfoLite.close();}
				});				
			}
		})
	},
	saveOrderChoosed: function(item){
		var group = item.toolManDragGroup
		var list = group.element.parentNode
		var id = list.getAttribute("id")
		if (id == null) return
		group.register('dragend', function(){
			drg=junkdrawer.serializeList($('#choosedPics #boxes')[0]);
			if(drg!=Draugiem.Gallery.initord){
				Draugiem.Gallery.initord=drg;
				D.console.info('save choosed drag\'n\'drop results: '+drg);
				Draugiem.Gallery.choosedReload();
			}
		});
	},	

	checkDragJsLoad: function(target, list_container){
		if (typeof(list_container)=='undefined') {
			list_container = 'boxes';
		}
		if(typeof(ToolMan)!='undefined'){
			dragsort = ToolMan.dragsort();
			junkdrawer = ToolMan.junkdrawer();

			if($((target?'#'+target+' ':'')+'#'+list_container+'')[0]){
				if(target=='choosedPics'){
					dragsort.makeListSortable($('#choosedPics #'+list_container+'')[0],this.saveOrderChoosed);
				}else{
					dragsort.makeListSortable($((target?'#'+target+' ':'')+'#'+list_container+'')[0],this.saveOrder);
				}
				Draugiem.Gallery.initord=junkdrawer.serializeList($((target?'#'+target+' ':'')+'#'+list_container+'')[0]);
			}
			D.console.info('drag\'n\'drop loaded');
		} else {
			Draugiem.Tools.dhtmlLoadScript("/js/drag/compl.js");
			window.setTimeout('Draugiem.Gallery.checkDragJsLoad(\''+target+'\',\''+list_container+'\');',100);
		}
	},
	
	checkUplJsLoad: function(){
	 	if(typeof(SWFUpload)!='undefined'){
			var settings_object = {
				id: 'drSwfUpl',
				upload_url : $("#SWFUploadForm").attr("action"),
				flash_url : "/img/swf/swfupload9a.swf",
				file_size_limit : $("#SWFUploadForm").attr("size"),
				file_types : $("#SWFUploadForm").attr("files"),
				file_types_description: "Web Image Files",
				
				requeue_on_error:true,

				swfupload_loaded_handler : Draugiem.Gallery.swfUplLoaded,
				
				file_dialog_start_handler : fileDialogStart,
				file_queued_handler : fileQueued,
				file_queue_error_handler : fileQueueError,
				file_dialog_complete_handler : fileDialogComplete,
				upload_start_handler : uploadStart,
				upload_progress_handler : uploadProgress,
				upload_error_handler : uploadError,
				upload_success_handler : uploadSuccess,
				upload_complete_handler : uploadComplete,
				
				post_params : { DS : sessid},
				
				button_image_url : "/img/g/SmallSpyGlassWithTransperancy_17x18.png",
				button_placeholder_id : "spanButtonPlaceholder",
				button_width: 345,
				button_height: 18,				
				button_cursor: SWFUpload.CURSOR.HAND,
				button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
			
				button_text : '<span class="button">'+($("#SWFUploadForm").attr("tp")=='pic'?galleryTxt['choose_upload_pics']:($("#SWFUploadForm").attr("tp")=='video'?galleryTxt['choose_upload_video']:'Choose files...'))+'</span>',
				button_text_style : '.button { font-family: Tahoma, Arial, sans-serif; font-size: 12pt; font-weight:bold}',
				button_text_top_padding : 0,
				button_text_left_padding : 18,
				button_action:  -110,
				
				custom_settings : {
					progressTarget : "fsUploadProgress",
					cancelButtonId : "btnCancel"					
				},
				debug_handler : Draugiem.Gallery.swfUplLoaded,
				debug: false
			};
			swfUplObj = new SWFUpload(settings_object);
		}else{
			window.setTimeout('Draugiem.Gallery.checkUplJsLoad();',100);
		}	
	},
	
	checkAjaxUplLoad: function(){
		var multi_selector = new MultiSelector(document.getElementById('fsUploadProgressAjax'),20);
		multi_selector.addElement(document.getElementById('fsFileElem'));
		$("#fsUploadProgressAjax").show();
		var new_element = document.createElement('input');
		new_element.type = 'hidden';
		new_element.name = 'ajax';
		new_element.value = 'true';
		document.getElementById('SWFUploadForm').appendChild(new_element);
	},
	
	swfUplLoaded: function(msg){
		$("#uplInfo").show();
		$("#SWFUpload").hide(); 
		D.console.info('swf upload loaded');
		/*if(typeof (msg) !='undefined'){
			$.post('/gal/debug.php',{
				DS:sessid,
				msg:msg
			});
		}*/
	},
	
	deleteAlbum: function (aid) {
		$.post ('/gal/submit/alb.php','del_alb=true&aid='+aid, function() { Draugiem.Gallery.x();return false; });
	},
	
	delPic: function(pic) {
		$.post ('/gal/submit/pic.php','del_pic=true&pic='+pic, function() { Draugiem.Gallery.x();return false; });
	},
	
	addPic: function(fid,aid,extra){
		if(typeof(extra)=='undefined'){extra='';}
		var size=this.getCoords();
		var left=parseInt((size[0])?(size[0]-500)/2:100);
		var top=parseInt((size[1])?(size[1]-300)/2:100);
		var newwin=window.open('/gal/dialog/newpic.php?fid='+fid+'&aid='+aid+'&extra='+extra+'&DS='+sessid,'pic','width=500,height=300,scrollbars=1,status=0,left='+left+',top='+top);
		if (window.focus) {newwin.focus();}
	},
	
	addVideo: function(fid,aid,extra){
		if(typeof(extra)=='undefined'){extra='';}
		var size=this.getCoords();
		var left=parseInt((size[0])?(size[0]-600)/2:100);
		var top=parseInt((size[1])?(size[1]-450)/2:100);	
		var newwin=window.open('/gal/dialog/newvideo.php?fid='+fid+'&aid='+aid+'&extra='+extra+'&DS='+sessid,'video','width=600,height=450,scrollbars=1,status=0,left='+left+',top='+top);
		if (window.focus) {newwin.focus();}
	},
	
	addVideoEmbed: function(fid,aid){
		var size=this.getCoords();
		var left=parseInt((size[0])?(size[0]-600)/2:100);
		var top=parseInt((size[1])?(size[1]-450)/2:100);	
		var newwin=window.open('/gal/dialog/newembed.php?fid='+fid+'&aid='+aid+'&DS='+sessid,'video','width=600,height=450,scrollbars=1,status=0,left='+left+',top='+top);
		if (window.focus) {newwin.focus();}
	},
	
	videoThumb: function(aid,fid,pic){
		var size=this.getCoords();
		var left=parseInt((size[0])?(size[0]-600)/2:100);
		var top=parseInt((size[1])?(size[1]-450)/2:100);	
		var newwin=window.open('/gal/dialog/newvideo.php?fid='+fid+'&aid='+aid+'&pic='+pic+'&force&step=4&DS='+sessid,'video','width=600,height=450,scrollbars=1,status=0,left='+left+',top='+top);
		if (window.focus) {newwin.focus();}
	},	

	addAlbum: function(fid){
		var size=this.getCoords();
		var left=parseInt((size[0])?(size[0]-500)/2:100);
		var top=parseInt((size[1])?(size[1]-250)/2:100);
		var newwin=window.open('/gal/dialog/newalb.php?fid='+fid+'&DS='+sessid,'alb','width=500,height=250,scrollbars=1,status=0,left='+left+',top='+top);
		if (window.focus) {newwin.focus();}
	},
	
	info: function(){
		InfoLite.open({text:'<div style="border:1px solid #ccc; margin:5px; background-color:white;padding:7px;font-weight:bold">'+Draugiem.Gallery.defaults.loading+'</div>'});
	},
	
	checkContextMenu: function(target){
	 	if(typeof($.fn.contextMenu)!='undefined'){
			D.console.info($((target?"#"+target+" ":"")+"div.thp").contextMenu('mnContext',{bindings:{
					'zoom': function(e){$(e).parent().parent().parent().click();window.setTimeout(function(){$('#selPicTh').click();},100);},
					'rtr': function(e){alert('rotate right '+e.id);},
					'rtl': function(e){alert('rotate left '+e.id);},
					'delete': function(e){alert('delete '+e.id);}
				}}).size()+' context menus added');
		}else{
			window.setTimeout('Draugiem.Gallery.checkContextMenu();',100);
		}		
	},

	cancel: function(e){
		Draugiem.Forms.formCancel=true;
		if (e && e.preventDefault)
			e.preventDefault(); // DOM style
		return false; // IE style
	},
	
	bug: function(){
		this.rq('/gal/show/bugform.php?ajax','usrAlb');
	},
	
	getCoords: function(){
		var ret=new Array();
		if (self.innerHeight){
			ret[0] = self.innerWidth;
			ret[1] = self.innerHeight;
		}else if (document.documentElement && document.documentElement.clientHeight){
			ret[0] = document.documentElement.clientWidth;
			ret[1] = document.documentElement.clientHeight;
		}else if (document.body){
			ret[0] = document.body.clientWidth;
			ret[1] = document.body.clientHeight;
		}
		return ret;
	},
	addSelected: function(target, div_id){
		if(typeof(target)!='undefined'){
			var trg=target;
		}else{
			var trg='choosedPics';
		}		
		if(typeof(ToolMan)=='undefined'){
			Draugiem.Tools.dhtmlLoadScript("/js/drag/compl.js");
		}	
		var ids='';
		$('#boxes li[class=box sel]').each(function(){ids+=(ids.length?',':'')+this.id;});
		if(ids){
			this.rq('/gal/admin/choosejsdata.php?ids='+ids+'&target='+trg+'&div_id='+div_id,'formResp');
		}
		this.choosedReload();
	},
	choosedReload: function(target){
		if(typeof(target)!='undefined'){
			var trg=target;
		}else{
			var trg='choosedPics';
		}		
		var ids='';
		$('#'+trg+' #boxes li').each(function(){ids+=(ids.length?',':'')+this.id;});
		$('#'+trg+'Inp').attr('value',ids);
		if(!ids){
			$('#'+trg+'Thumb').attr('value','');
		}else{
			$('#'+trg+' #boxes li:last').click();
		}
	},

	highlightStars: function(cnt){
        this.unhighlightStars(true);
        for(i=1;i<=cnt;i++){
            $('#video_rating_star_'+i).attr('src',pimg+'/img/star_on.gif');
        }
	},

	unhighlightStars: function(forced){
		if (this.selectedStars == 0 || forced){
			for(i=1;i<=5;i++){
				$('#video_rating_star_'+i).attr('src',pimg+'/img/star_off.gif');
			}
		}else{
			this.highlightStars(this.selectedStars);
		}
	},

	selectStars: function(cnt){
	    this.selectedStars = cnt;
	    $('#videoRating').val(this.selectedStars);
	},
	
	videoPolicy: function(pic){
		InfoBox.iframe('/gal/dialog/videoTP.php?pic='+pic+'&DS='+sessid,{width:550,height:400});
	}
}; // Draugiem.Gallery = {

if( typeof xGallery != 'undefined' ){
	Draugiem.Gallery.defaults.delcom = xGallery['conf_del_comment'];
	Draugiem.Gallery.defaults.sTagAdd = xGallery['tg_mark_fr'];
	Draugiem.Gallery.defaults.sTagCancel = xGallery['tg_mark_fr_c']; 
	Draugiem.Gallery.defaults.sTagHint = xGallery['tg_mark_hint']; 
	Draugiem.Gallery.defaults.sTagEnable = xGallery['tg_show_tags']; 
	Draugiem.Gallery.defaults.sTagDisable = xGallery['tg_hide_tags']; 
}

function playerReady(obj){
	var id = obj.id;
	D.console.info('player '+id+' loaded');	
	var player = document.getElementById(id);
	var plVolume=Draugiem.Cookie.read('drVPlVol');
	if(plVolume){
		player.sendEvent('VOLUME',plVolume);
	}else{
		player.sendEvent('VOLUME',80);	
	}
	player.addControllerListener("VOLUME","videoVolumeTracker");
};

function videoVolumeTracker(percentage,id,client,version){
	D.console.info(percentage.percentage);
	Draugiem.Cookie.create('drVPlVol',percentage.percentage);
};

function var_dump(data,addwhitespace,safety,level) {
	var rtrn = '';
	var dt,it,spaces = '';
	if(!level) {level = 1;}
	for(var i=0; i<level; i++) {
		spaces += '   ';
	}
	if(typeof(data) != 'object') {
		dt = data;
		if(typeof(data) == 'string') {
			if(addwhitespace == 'html') {
				dt = dt.replace(/&/g,'&amp;');
				dt = dt.replace(/>/g,'&gt;');
				dt = dt.replace(/</g,'&lt;');
			}
			dt = dt.replace(/\"/g,'\"');
			dt = '"' + dt + '"';
		}
		if(typeof(data) == 'function' && addwhitespace) {
			dt = new String(dt).replace(/\n/g,"\n"+spaces);
			if(addwhitespace == 'html') {
				dt = dt.replace(/&/g,'&amp;');
				dt = dt.replace(/>/g,'&gt;');
				dt = dt.replace(/</g,'&lt;');
			}
		}
		if(typeof(data) == 'undefined') {
			dt = 'undefined';
		}
		if(addwhitespace == 'html') {
			if(typeof(dt) != 'string') {
				dt = new String(dt);
			}
			dt = dt.replace(/ /g,"&nbsp;").replace(/\n/g,"<br>");
		}
		return dt;
	}
	for (var x in data) {
		if(safety && (level > safety)) {
			dt = '*RECURSION*';
		} else {
			try {
				dt = var_dump(data[x],addwhitespace,safety,level+1);
			} catch (e) {continue;}
		}
		it = var_dump(x,addwhitespace,safety,level+1);
		rtrn += it + ':' + dt + ',';
		if(addwhitespace) {
			rtrn += '\n'+spaces;
		}
	}
	if(addwhitespace) {
		rtrn = '{\n' + spaces + rtrn.substr(0,rtrn.length-(2+(level*3))) + '\n' + spaces.substr(0,spaces.length-3) + '}';
	} else {
		rtrn = '{' + rtrn.substr(0,rtrn.length-1) + '}';
	}
	if(addwhitespace == 'html') {
		rtrn = rtrn.replace(/ /g,"&nbsp;").replace(/\n/g,"<br>");
	}
	return rtrn;
};

function changepic(id){ 
  window.document.carousel.SetVariable("actelement",id);
}
function carousel_DoFSCommand(command, args){ 
  if (command == "showpic") { 
    var param=args.split(",");
    Draugiem.Gallery.p(param[0],param[1],param[2],param[3],param[4]);
  }
}

$(document).ready(function(){Draugiem.Gallery.init();}); 


/*
	Image Tagger, Deniss
*/

/* Objects */
var oSwitcher = 'taggedSwitcher';
var oImgArea = 'imgArea';
var oFriendsForm = 'taggedFriendsForm';
var oFriendsSearchInput = 'contact_list';
var oFriendsFormCancelBtn = 'taggedFriendsFormCancel';
var oFriendsFormOK = 'taggedFriendsFormOK';
var oSelectedUID = 'userID';
var oSelectedPICID = 'picID';
var oTagged = 'tagerID';
var oSelectedAID = 'albumID';
var prevLink = 'overlayPrevLink';
var nextLink = 'overlayNextLink';
var oTagsHolder = 'picTags';
		
/* Variables */
var bEnabled = false;
var x1, x2, y1, y2, width, height = 0;
var mousex, mousey = 0;
		
/* Strings */


		
/* Functions */
function taggedLoader () {	
	// Setting event handlers here
	$('#'+oSwitcher).html (Draugiem.Gallery.defaults.sTagAdd);
	return true;
}

function setButtonHandlers () {
	$('#'+oFriendsFormCancelBtn).click (taggedResetRectangle);
	$('#'+oFriendsFormOK).click (taggedSelectUser);
}

function taggedInitImgArea(mode){
	switch (mode) {
		case 'full': {
		   $('#'+oImgArea).imgAreaSelect ({
				selectionColor: 'black', 
				borderColor1 : 'white',
				borderColor2 : 'white',
				minHeight :10,
				minWidth: 10,
				maxWidth:400,
				maxHeight:300,
				outerOpacity : 0,
				selectionOpacity : 0.4,
				autoHide:false,
				movable:false,
				resizable:false,
				disable:false,
				hide:false,
				parent:'#'+oImgArea,
				onSelectEnd: taggedSelectEnd
			}); 

			break;	
		}
		case 'hidden': {
			$('#'+oImgArea).imgAreaSelect ({
				hide : true,
				disable:true
			}); 
			break;	
		}
		case 'disabled': {
			$('#'+oImgArea).imgAreaSelect ({
			disable:true
			}); 
			break;	
		}
	}
}

function taggedLoadImgArea (mode){
	//Draugiem.Tools.loadScript("/js/jquery.imgareaselect-0.4.2.js",function(){taggedInitImgArea(mode);});	
	taggedInitImgArea(mode)
}
		
function taggedSwitcher () {
	$('#'+oSwitcher).html(bEnabled ? Draugiem.Gallery.defaults.sTagAdd : Draugiem.Gallery.defaults.sTagCancel);
	$('#'+oImgArea).css('cursor',bEnabled ? 'default':'crosshair');
	bEnabled = !bEnabled;	
	if (bEnabled) {
		$('#'+prevLink).css('display','none');
		$('#'+nextLink).css('display','none');
		//$('#'+oTagsHolder).css('display','none');
		$('#'+oTagsHolder+' a').addClass('hov');
		$('#'+oTagsHolder+' a').click(function(){return false;});
		$('#'+oTagsHolder).css('display','block'); 
		
		
		/*
		if(typeof(imgAreaSelect)=='undefined'){  // pārbaude lai nelādētu vēlreiz
			Draugiem.Tools.loadScript("/js/compl.js");
			Draugiem.Tools.loadScript("/js/jquery.imgareaselect-0.4.2.js");
		}
		Draugiem.Tools.loadScript("/js/compl.js", Draugiem.Tools.loadScript("/js/jquery.imgareaselect-0.4.2.js",function(){taggedInitImgArea('full');}));
		*/
		taggedLoadImgArea('full')
		
		$('#taggedHint').css('display','block'); 
		
	} else {
		$('#'+prevLink).css('display','block');
		$('#'+nextLink).css('display','block'); 
		$('#taggedHint').css('display','none'); 
		//$('#'+oTagsHolder).css('display','block');
		$('#'+oTagsHolder+' a').removeClass('hov');
		$('#'+oTagsHolder+' a').unbind('click');
		
		taggedHideFriendsList();
		taggedResetRectangle();
		taggedDisableRectangle(); 
	}
	
	return true;
}

function taggedSelectEnd (img,selection) {
	x1 = selection.x1; y1 = selection.y1; x2 = selection.x2; y2 = selection.y2; width=selection.width; height=selection.height;
	taggedDisableRectangle();
	/*
	var posx = (imgOfsX + x1) + 20;
	var posy = (imgOfsY + y1) + 20;
	*/
	posx = 160;
	posy = 150;
	taggedDisplayFriendsList(posx,posy); 
}

function taggedDisableRectangle () {
	taggedLoadImgArea('disabled');
}


function taggedDisplayFriendsList (x,y) {
	var div = document.createElement ('div');
	div.id = oFriendsForm;
	$('body #picImg').append(div);
	
	var cssObj = {
		display:"block",
        left: x+"px",
        top: y+"px"
    }
	$('#'+oFriendsForm).css(cssObj);
	
	$.ajax({
		url:"/gal/show/tag_form.php?picid="+picID+"&aid="+aID+"&tager="+tagerID,
		success: function(txt){$('#'+oFriendsForm).html(txt); $('#'+oFriendsSearchInput).focus(); },
		error:function(txt){$('#'+oFriendsForm).append("<li>kluda "+txt+"</li>");}
	}); 
	 
}

function taggedHideFriendsList () {
	$('#'+oFriendsForm).remove();
	$('#'+oFriendsSearchInput).attr('value','');
	$('#'+oSelectedUID).attr('value','0');
}



function taggedResetRectangle () {
	if (document.getElementById(oImgArea)) {
		taggedLoadImgArea('hidden');
		taggedHideFriendsList();
	}
}

function taggedSendSave (id) {
	var picid = document.getElementById(oSelectedPICID).value;
	var albumid = document.getElementById(oSelectedAID).value;
	var tager = document.getElementById(oTagged).value;
	if (id) {
		$.ajax({
		url:"/gal/submit/tag.php?task=adduser&picid="+picid+"&albumid="+albumid+"&userid="+id+"&x1="+x1+"&y1="+y1+"&x2="+x2+"&y2="+y2+"&tager="+tager,
			success: function(result){ taggedDataSaved(result);},
			error:function(txt){$('#'+oFriendsForm).append("<li>kluda "+txt+"</li>");}
		}); 
	}
}

function taggedSelectUser () {
	var id = document.getElementById(oSelectedUID).value;
	taggedSendSave (id);
}

function taggedDataSaved (result) {
	var d = result.split('|');
	if (d[0] == 'execute') { 
		bEnabled = false;	
		taggedResetRectangle();
		eval (d[1]);
	}
	if (d[0] == 'msg') {
		alert(d[1]);	
	}
}

function taggedDeleteTag (id) {
	if (id) {
		$('tag_'+id).remove();
		$.ajax({
		url:"/gal/submit/tag.php?task=deltag&picid="+picID+"&albumid="+aID+"&id="+id+"&tager="+tagerID,
			success: function(result){ taggedDataSaved(result);}
		}); 
	}
}

function taggedPicReload(a,p,l,u,r,g) {
	Draugiem.Gallery.lastRq='';
	Draugiem.Gallery.lastRqArr=new Array();
	Draugiem.Gallery.p(u,a,l,r,g);
}

function taggedToggleTags() {
	var state = $('#'+oTagsHolder).css('display');
	var text = state=='block'?Draugiem.Gallery.defaults.sTagEnable:Draugiem.Gallery.defaults.sTagDisable;
	$('#'+oTagsHolder).css('display',state=='block'?'none':'block');
	$('#tagsDisableLink').html(text);
	$.ajax({
		url:"/gal/submit/tag.php?task=toggletags&state="+(state=='block'?0:1),
			success: function(result){;},
			error:function(txt){$('#'+oFriendsForm).append("<li>kluda "+txt+"</li>");}
		}); 
}


function taggedCloseMsg() { 
	$('#taggedHint').remove();  
	$.ajax({
		url:"/gal/submit/tag.php?task=closemsg",
			success: function(result){;},
			error:function(txt){$('#'+oFriendsForm).append("<li>kluda "+txt+"</li>");}
		}); 	
}