
$(document).ready(function(){

	activateDrops();
	activateRating();


	// Logo click
	$("a#logolink").mousedown(function(){
		$("div#logo").addClass("mousedown");
	}).mouseup(function(){
		$("div#logo").removeClass("mousedown");
	}).mouseout(function(){
		$("div#logo").removeClass("mousedown");
	}).click(function(){
		$("div#logo").removeClass("mousedown");
	});


	// Menu item click
	$(".menuitem, .menuitemact").click(function(){
		var link = $(this).find("a.menulink").attr("href") || "";
		if(link!=""){document.location.href = link;}
	});
	
	// Product click
	$(".productbox, .clickinner").click(function(){
		var link = $(this).find(".noclick").filter(":first").attr("href") || "";
		//var link = $(this).find("a.prodlink").attr("href") || "";
		if(link!=""){document.location.href = link;}
	});
	
	
	// Clear floats if longer text
	$(".flclear").each(function(){
		if($(this).position().left == 20){
			$(this).css("float","none");
			$(this).css("clear","both");
			$(this).css("margin-left","0");
		}
	});
	
	
	// Comment reply
	$(".commholder").hover(function(){
		$(".reply", this).css("visibility","visible");
	},function(){
		$(".reply", this).css("visibility","hidden");
	}
	);
	
	
	// No default action on click
  $(".noclick").live("click", function(event){
	  event.preventDefault();
	});
  
  // No bubbling
  $(".nobubble").click(function(event){
  	event.stopPropagation();
	});

	
});

//////////////////////////////////// PeelAd

function addpeel(peelp, url, newwin, imgp, swidth, sheight, bwidth, bheight, pos){
	document.write('<div id="peelcont" style="width:' + swidth + 'px; height:' + sheight + 'px; position:absolute; z-index:9000; top:0; left:0; overflow:hidden;"><div id="peelinner" style="width:' + bwidth + 'px; height:' + bheight + 'px; position:absolute; z-index:9001; top:0; left:0;"><div id="peel"></div></div></div>');
	if(pos == "tr"){
		document.getElementById("peelcont").style.left = "auto";
		document.getElementById("peelcont").style.right = 0;
		document.getElementById("peelinner").style.left = "auto";
		document.getElementById("peelinner").style.right = 0;
	}
	if(pos == "br"){
		document.getElementById("peelcont").style.left = "auto";
		document.getElementById("peelcont").style.right = 0;
		document.getElementById("peelcont").style.top = "auto";
		document.getElementById("peelcont").style.bottom = 0;
		document.getElementById("peelcont").style.position = "fixed";
		document.getElementById("peelinner").style.left = "auto";
		document.getElementById("peelinner").style.right = 0;
		document.getElementById("peelinner").style.top = "auto";
		document.getElementById("peelinner").style.bottom = 0;
	}
	if(pos == "bl"){
		document.getElementById("peelcont").style.top = "auto";
		document.getElementById("peelcont").style.bottom = 0;
		document.getElementById("peelcont").style.position = "fixed";
		document.getElementById("peelinner").style.top = "auto";
		document.getElementById("peelinner").style.bottom = 0;
	}
	swfobject.embedSWF(peelp, "peel", bwidth, bheight, "8.0.0", "/inc/expressinstall.swf", {clickTAG:url, imgpath:imgp, position:pos, smallwidth:swidth, smallheight:sheight, openblank:newwin}, {wmode:"transparent", allowscriptaccess:"sameDomain"}, {});
	
}

function peelstart(bwidth, bheight){
	document.getElementById("peelcont").style.width = bwidth + "px";
	document.getElementById("peelcont").style.height = bheight + "px";
	getFlashMovie("peel").doPeel();
}

function peelstop(swidth, sheight){
	document.getElementById("peelcont").style.width = swidth + "px";
	document.getElementById("peelcont").style.height = sheight + "px";
}


//////////////////////////////////// Flash movie and IE Browser

function getFlashMovie(movieName) {
	if (Browser.Version() <= 8){return window[movieName];}else{return document[movieName];}
}

var Browser = {
	Version: function() {
		var version = 999;
		if (navigator.appVersion.indexOf("MSIE") != -1){
			version = parseFloat(navigator.appVersion.split("MSIE")[1]);
			return version;
		}
	}
}


//////////////////////////////////// N

function re(cels) {
	document.location.href=cels;	
}

function setStats(id,db,rel){
	var url = '/inc/data.php?dofor=setstats&id='+id+'&db='+db;
	new httpRequest(url,null,'GET',document.location.href=rel,true);
}

function conDel(itm,p){
	var agree=confirm("Vai tiešām vēlies dzēst šo "+itm+"?");
	if (agree) re(p);
	else return false ;
}

function checkBadDates(){
	var bgid = document.getElementById('ban_bgid').options[document.getElementById('ban_bgid').selectedIndex].value;
	var fd = document.getElementById('ban_fd').value;
	var td = document.getElementById('ban_td').value;
	
	if((fd.length > 0) && (td.length > 0)){
		var url = '/inc/data.php?dofor=chkbaddates&td='+td+'&fd='+fd+'&bgid='+bgid;
		new httpRequest(url,null,'GET',msgBadDates,true);
	}
}

function msgBadDates(r){
	var err = 0;
	eval(r);
	if(err == 1){
		document.getElementById('ban_fd').value = '';
		document.getElementById('ban_td').value = '';
		document.getElementById('banprice').innerHTML = '0.00';
		alert('Lūdzu izvēlieties pilnus publikācijas laika periodus.\nJa vēlaties publikācijas periodu pēc aizņemtā datuma, tad ielādējiet jaunu banneri.\nNeskaidrību gadījumā rakstiet atlaides@atlaides.lv.');
	} else {
		recountBan();
	}
}

function getBadDates(){
	document.getElementById('ban_fd').value = '';
	document.getElementById('ban_td').value = '';
	document.getElementById('banprice').innerHTML = '0.00';
	var bgid = document.getElementById('ban_bgid').options[document.getElementById('ban_bgid').selectedIndex].value;
	var url = '/inc/data.php?dofor=baddates&bgid='+bgid;
	new httpRequest(url,null,'GET',setBadDates,true);
}

function setBadDates(r){
	var bad;
	eval(r);
	document.getElementById('disdates').value = bad;
}

function recountBan(){
	var days = diff = 0;	
	var fd = document.getElementById('ban_fd').value;
	var td = document.getElementById('ban_td').value;
	
	if(fd.length > 0 && td.length > 0){
		var dt1  = parseInt(fd.substring(8,10),10);
		var mon1 = parseInt(fd.substring(5,7),10);
		var yr1  = parseInt(fd.substring(0,4),10);
		var dt2  = parseInt(td.substring(8,10),10);
		var mon2 = parseInt(td.substring(5,7),10);
		var yr2  = parseInt(td.substring(0,4),10);
		var date1 = new Date(yr1, mon1, dt1);
		var date2 = new Date(yr2, mon2, dt2);

		diff = date2 - date1;
		days = Math.round(diff/(1000*60*60*24));
		days++;
		price = 0;
		bangid = document.getElementById('ban_bgid').options[document.getElementById('ban_bgid').selectedIndex].value;
		if(bangid == 3 || bangid == 4 || bangid == 5){
			if(days < 8) price = days;
			else if(days > 7 && days < 15) price = days * 0.9;
			else if(days > 14 && days < 31) price = days * 0.8;
			else price = days * 0.5;
		} else if(bangid == 6 || bangid == 8){
			if(days < 8) price = days * 2;
			else if(days > 7 && days < 15) price = days * 1.7;
			else if(days > 14 && days < 31) price = days * 1.5;
			else price = days;
		} else if(bangid == 7){
			if(days < 8) price = days * 20;
			else if(days > 7 && days < 15) price = days * 18;
			else if(days > 14 && days < 31) price = days * 15;
			else alert("Šī tipa bannerim maksimālais termiņš ir 30 dienas!");
		}
		document.getElementById('banprice').innerHTML = price.toFixed(2);
	}

}



//////////////////////////////////// HighSlide

hs.graphicsDir = '/inc/highslide/graphics/';
hs.outlineType = 'rounded-white';
hs.wrapperClassName = 'draggable-header';
hs.showCredits = false;
hs.expandDuration = 0;
hs.restoreDuration = 0;
hs.transitions = ['expand', 'crossfade'];
//hs.dimmingOpacity = 0.7;
hs.dimmingOpacity = 0;
hs.dimmingDuration = 0;

function hsgroupctrls(groupname,showthumbs){
	if(showthumbs == true){
		hs.addSlideshow({
			slideshowGroup: groupname,
			interval: 5000,
			repeat: false,
			useControls: true,
			fixedControls: 'fit',
			overlayOptions: {
				opacity: .75,
				position: 'bottom center',
				hideOnMouseOut: true
			},
				thumbstrip: {
					position: 'above',
					mode: 'horizontal',
					relativeTo: 'expander'
				}
		});
	}else{
		hs.addSlideshow({
			slideshowGroup: groupname,
			interval: 5000,
			repeat: false,
			useControls: true,
			fixedControls: 'fit',
			overlayOptions: {
				opacity: .75,
				position: 'bottom center',
				hideOnMouseOut: true
			}
		});
	}
}

function hsresize() {
   var obj = window.parent.hs;
   if(obj){
   		var exp = obj.getExpander();
   		if (exp) exp.reflow();
   }
}



//////////////////////////////////// Countdown

//// Countdown
	$.countdown.regional['lv'] = {
		labels: ['Gadi', 'Mēneši', 'Nedēļas', 'Dienas', 'Stundas', 'Minūtes', 'Sekundes'],
		labels1: ['Gads', 'Mēnesis', 'Nedēļa', 'Diena', 'Stunda', 'Minūte', 'Sekunde'],
		compactLabels: ['g', 'm', 'n', 'd'],
		timeSeparator: ':',
		isRTL: false
	};
	//$.countdown.setDefaults($.countdown.regional['lv']);
	
function startcount(objid,exptime) {
	$.countdown.setDefaults($.countdown.regional['lv']);
	$("#" + objid).countdown({
		//until: new Date(2013, 8-1, 15),
		until:exptime,
		//compact:true,
		format:'dHMS',
		alwaysExpire:true,
		onExpiry:stopbuy,
		expiryText:'Piedāvājums beidzies',
		layout:
			//'{o<}<b>{o10}{o1}{ol}</b>{o>}' + 
			'{d<}<b>{dn} {dl}</b>{d>} ' + 
	    '{hnn}h{sep}{mnn}m{sep}{snn}s'
	});
}
	
function stopbuy() {
	$("#buybtn").hide();
	$("#dealoff").show();
}



//////////////////////////////////// Dropdown

function activateDrops(){
	
	var dropover = false;
	
	$(".dropdown>.btntxt").click(function(){
		var clobj = $(this);
		var drobj = $(this).parent();
		$(".dropdowncont").not(drobj).hide('fade',500);
		$(".dropdown>.btntxt").not(clobj).removeClass("act");
		$(this).toggleClass("act");
		if($(this).next(".dropdowncont").is(':hidden')){
			$(this).next(".dropdowncont").show('fade',500);
		}else{
			$(this).next(".dropdowncont").hide('fade',500);
		}
	});
	
	$("body").click(function(){
		if(dropover == false){
			$(".dropdowncont:visible").siblings(".btntxt:first").removeClass("act");
			$(".dropdowncont:visible").hide('fade',500);
		}
	});
	
	$(".dropdown").mouseleave(function(){
		dropover = false;
	}).mouseenter(function(){
		dropover = true;
	});
	
	/*$(".dropdown").click(function(){
		event.stopPropagation();
	}*/
	
	$(".dropdown:not(.nomouseout)").mouseleave(function(){
		$(this).oneTime(1000, function(){
			if($(this).find(".dropdowncont").is(':visible')){
				$(this).find(".dropdowncont").hide('fade',500);
				$(this).find(".btntxt:first").removeClass("act");
			}
		});
	}).mouseenter(function(){
		$(this).stopTime();
	});
	
	$(".dropdowncont .btn_close").click(function(){
		$(this).parent(".dropdowncont").hide('fade',500);
		$(this).parent(".dropdowncont").prev(".btntxt").removeClass("act");
	});
	
}



//////////////////////////////////// Rating

function activateRating(){

	$('.ratings_star').hover(function(){
		$(this).prevAll().andSelf().each(function(){
			var src1 = $(this).attr('src'); // initial src
			var newSrc = src1.substring(0, src1.lastIndexOf('.')); // let's get file name without extension
			$(this).attr('src', newSrc + '_over.' + /[^.]+$/.exec(src1)); //last part is for extension
		});
		$(this).nextAll().each(function(){
			var src1 = $(this).attr('src'); // initial src
			var newSrc = src1.substring(0, src1.lastIndexOf('.')); // let's get file name without extension
			$(this).attr('src', newSrc + '_out.' + /[^.]+$/.exec(src1)); //last part is for extension
		});
	},function(){
		$(this).prevAll().andSelf().each(function(){
			var src1 = $(this).attr('src'); // initial src
			var newSrc = src1.substring(0, src1.lastIndexOf('_over.')); // let's get file name without extension
			$(this).attr('src', newSrc + '.' + /[^.]+$/.exec(src1)); //last part is for extension
		});
		$(this).nextAll().each(function(){
			var src1 = $(this).attr('src'); // initial src
			var newSrc = src1.substring(0, src1.lastIndexOf('_out.')); // let's get file name without extension
			$(this).attr('src', newSrc + '.' + /[^.]+$/.exec(src1)); //last part is for extension
		});
	});

	$('.ratings_star').click(function(event){
		var x = $(this).attr('id');
		var s = x.substr(1).split('-');
		var id = s[0];
		var star = s[1];
		setRate(id,star);
	});
	
}

function setRate(pid,star){
	var url = '/inc/data.php?for=setrate&pid='+pid+'&star='+star;
	new httpRequest(url,null,'GET',showRateMsg,true);
}

function showRateMsg(r){
	var msg = s = '';
	var rate = pid = 0;
	eval(r);
	
	x = s.split('-');
	for(var i=1; i<6; i++) {
		document.getElementById('s'+pid+'-'+i).src = '/img/icons/star1'+x[i-1]+'.png';
	}
	
	document.getElementById('sc'+pid).innerHTML = rate;
	alert(msg);
}



//////////////////////////////////// Ieteikt

function DraugiemSay(title, url, titlePrefix){
 window.open(
  'http://www.draugiem.lv/say/ext/add.php?title=' + encodeURIComponent( title ) +
  '&link=' + encodeURIComponent( url ) +
  ( titlePrefix ? '&titlePrefix=' + encodeURIComponent( titlePrefix ) : '' ),
  '',
  'location=1,status=1,scrollbars=0,resizable=0,width=550,height=450'
 );
 return false;
}

function TwitterSay(text, url, via){
 window.open(
  'http://twitter.com/share?text=' + encodeURIComponent( text ) +
  '&url=' + encodeURIComponent( url ) +
  ( via ? '&via=' + encodeURIComponent( via ) : '' ),
  '',
  'location=1,status=1,scrollbars=0,resizable=0,width=550,height=450'
 );
 return false;
}

function FacebookSay(t, u){
 window.open(
  'http://www.facebook.com/sharer.php?t=' + encodeURIComponent( t ) +
  '&u=' + encodeURIComponent( u ),
  '',
  'location=1,status=1,scrollbars=0,resizable=0,width=550,height=450'
 );
 return false;
}



//////////////////////////////////// Set field text, empty, focus

function setfieldempty(obj,txt){
	if(obj.value == txt){
		obj.value = '';
	}
}

function setfieldtext(obj,txt){
	if(obj.value == ''){
		obj.value = txt;
	}
}

function setfocus(objid){document.getElementById(objid).focus();}



//////////////////////////////////// Show / Hide

function showhide(hidewhat){
	hideobject = document.getElementById(hidewhat);
	hideobject.style.display = hideobject.style.display=="none" ? "" : "none";
}

function show(showwhat){
	showobject = document.getElementById(showwhat);
	showobject.style.display = "";
}

function hide(hidewhat){
	hideobject = document.getElementById(hidewhat);
	hideobject.style.display = "none";
}




//////////////////////////////////// Check Checkboxes

function checkall(group){
	for(i = 0; i < group.length; i++){
		group[i].checked = true;
	}
}

function uncheckall(group){
	for(i = 0; i < group.length; i++){
		group[i].checked = false;
	}
}

function select_all(name, value) {
	var forminputs = document.registerform.getElementsByTagName('input');
	for (i = 0; i < forminputs.length; i++) {
		var regex = new RegExp(name, "i");
		if (regex.test(forminputs[i].getAttribute('name'))) {
			if (value == '1') {
				forminputs[i].checked = true;
			} else {
				forminputs[i].checked = false;
			}
		}
	}
}

function checkuncheck(what){
	$checkuncheckobject = document.getElementById(what);
	$checkuncheckobject.checked = $checkuncheckobject.checked=="" ? "true" : "";
}



//////////////////////////////////// N

function conf(act,itm){
	var agree=confirm("Vai tiešām vēlies dzēst šo "+itm+"?");
	if (agree) re(act);
	else return false ;
}

/// LOAD PIC COMMENT

function loadPicTitle(id){
	if(id == '') id = document.getElementById('selpic').value;
	else document.getElementById('selpic').value = id;
	
	if(id == '') return false;

	a = document.getElementsByTagName('img');
	for(i=0;i<a.length;i++){
		if(a[i].id.substr(0,2) == 'pc')	a[i].src = '/img/icons/comment.gif';
	}
	
	var m = 'pc'+id.toString();
	document.getElementById(m).src = '/img/icons/comment_on.gif';
	
	var ln = 'lv';
	var url = '/inc/data.php?dofor=com&ln='+ln+'&id='+id;
	new httpRequest(url,null,'GET',fillTitle,true);
}

function fillTitle(r) {
	var title = document.getElementById('title');
	eval(r);
}

function saveTitle() {
	var title = document.getElementById('title').value;
	var id = document.getElementById('selpic').value;
	var ln = 'lv';
	if(id == '') return false;
	
	var url = '/inc/data.php?dofor=savecom&id='+id+'&title='+title+'&ln='+ln;
	new httpRequest(url,null,'GET',showMsg,true);	
}

function showMsg(r) {
	var msg;
	eval(r);
	alert(msg);
}

/// PIC GRID LIST

function getPicGrid(db,id){
	var url = '/inc/data.php?dofor=grid&db='+db+'&id='+id;
	new httpRequest(url,null,'GET',showPicGrid,true);
}

function showPicGrid(r){
	var rowcnt;
	var data;
	document.getElementById('rowcnt').innerHTML = '';
	document.getElementById('picarr').innerHTML = '';
	eval(r);
	document.getElementById('rowcnt').innerHTML = unescape(rowcnt);
	document.getElementById('picarr').innerHTML = unescape(data);
	
	$(function(){
		$('.column').sortable({
			connectWith: '.column',
			handle: 'span',
			cursor: 'move',
			placeholder: 'placeholder',
			forcePlaceholderSize: true,
			opacity: 0.4,
			stop: function(event, ui){
				$(ui.item).find('span').click();
				var sortorder='';
				$('.column').each(function(){
					var itemorder=$(this).sortable('toArray');
					var columnId=$(this).attr('id');
					sortorder+=columnId+'='+itemorder.toString();
				});
				savePicOrder(sortorder);
				/*Pass sortorder variable to server using ajax to save state*/
			}
		})
		.disableSelection();
	});
}

/// PIC SORT

function savePicOrder(arr){
	var url = '/inc/data.php?dofor=picord&'+arr;
	new httpRequest(url,null,'POST',nothin,true);
}

function nothin(){}

function chPersona(o){
	v = o.options[o.selectedIndex].value;
	if(v == 0){
		document.getElementById('bill_j_title_title').innerHTML = 'Vārds, uzvārds';
		document.getElementById('bill_j_reg_title').innerHTML = 'Personas kods';
	} else {
		document.getElementById('bill_j_title_title').innerHTML = 'Uzņēmuma nosaukums';
		document.getElementById('bill_j_reg_title').innerHTML = 'Reģistrācijas nr.';
	}
}

function chTerm(r){
	var term = r.value;
	var dienas = 7;
	var ned = 1;
	if(term > 0){
		dienas = term * 30;
		ned = term * 4;
	}
	
	document.getElementById('bill_prod_col').innerHTML = (dienas * 0.1).toFixed(2);
	document.getElementById('bill_prod_cnt_50').innerHTML = (ned * 0.75).toFixed(2);
	document.getElementById('bill_prod_cnt_100').innerHTML = (ned * 1.25).toFixed(2);
	document.getElementById('bill_prod_cnt_200').innerHTML = (ned * 2).toFixed(2);
}




