var timerID = null;
var timerRunning = false;
var userExpiry = 365 * 24 * 60 * 60 * 1000;

function setLanguage(lang) {
	var curLang = getCookie("lang");
	var now = new Date();
      // Fix the bug in Navigator 2.0, Macintosh
    fixDate(now);
	now.setTime(now.getTime() + userExpiry);
	// delete old cookie
	deleteCookie(curLang);					
	// set up new cookie
	setCookie("lang", lang, now);
	// simple trick to reload the current document
	self.location = self.location;	

}

function getCookieVal (offset) {
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1) { endstr = document.cookie.length; }
	return unescape(document.cookie.substring(offset, endstr));
}

// Input value:
// name - name of the desired cookie
// * return string containing value of specified cookie or null if cookie does not exist
function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

// Input values:
// name - name of the cookie
// value - value of the cookie
// [expires] - expiration date of the cookie (defaults to end of current session)
// [path] - path for which the cookie is valid (defaults to path of calling document)
// [domain] - domain for which the cookie is valid (defaults to domain of calling document)
// [secure] - Boolean value indicating if the cookie transmission requires a secure transmission
// * an argument defaults when it is assigned null as a placeholder
// * a null placeholder is not required for trailing omitted arguments
function setCookie(name, value, expires, path, domain, secure) {
    var curCookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");

    document.cookie = curCookie;
    return(true);
}

// Input values:
// name - name of the cookie
// [path] - path of the cookie (must be same as path used to create cookie)
// [domain] - domain of the cookie (must be same as domain used to create cookie)
// * path and domain default if assigned null or omitted if no explicit argument proceeds
function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" + 
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

// Input value:
// date - any instance of the Date object
// * hand all instances of the Date object to this function for "repairs"
function fixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
}

function loginToggle()
{
	new Effect.toggle($('placeholder'), 'blind', {duration: 1.0});
}

function languageToggle()
{
	new Effect.toggle($('languagebar'), 'blind', {duration: 1.0});
}

function egoBoost()
{
	$('footer-content').style.position = 'fixed';
	$('footer-content').style.bottom = '0px';
	$('footer-content').style.width = '100%';
	new Effect.BlindDown($('egoboost'));	
	setTimeout("new Effect.BlindUp($('egoboost'), { duration: 1.0 });", 5000);
	setTimeout("document.location.href = document.location.href;", 6000);
	return false;
}

function setSubCategory(obj)
{
	if($('txtSubCategory') && obj) {
		$('txtSubCategory').value = obj.value;
	}
	else {
		return;
	}
}

function doSave()
{
	var theform = document.forms['form1'];
	theform.action = "?p=admin_product&cid=" + getParam('cid') + "&scid=" + getParam('scid') + "&pid=" + getParam('pid') + "&action=save";
	theform.submit();
} 

function doSaveNews()
{
	var theform = document.forms['form1'];
	theform.action = "?p=admin_news&nid=" + getParam('nid') + "&action=save";
	theform.submit();
} 

function getParam(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null ) {
    return "";
  } 
  else {
    return results[1];
  }
}

function sz(t) 
{
	a = t.value.split('\n');
	b=1;
	for (x=0;x < a.length; x++) {
 		if (a[x].length >= t.cols)  {
 			b+= Math.floor(a[x].length/t.cols);
 		}
 	}
	b+= a.length;
	if (b > t.rows) {	
		t.rows = b;
	}	
}

function changeOpacity(id)
{
	$opacityStatus = $('status'+id);
	if($opacityStatus.value==0){
		 new Effect.Opacity('el'+id, {duration:0.5, from:1.0, to:0.3});
		$opacityStatus.value=1; 
	} else {
		new Effect.Opacity('el'+id, {duration:0.5, from:0.3, to:1});
		$opacityStatus.value=0; 
	}
}

function onOpacity(id)
{
	new Effect.Opacity('img_' + id, {duration:0.5, from:1.0, to:0.5});
}

function offOpacity(id)
{
	new Effect.Opacity('img_' + id, {duration:0.5, from:0.5, to:1.0});
}

function doCancel()
{
	var fullUrl = document.location.href;
	
	if (document.referrer != '')
	{
		document.location.href = document.referrer;
	}
	else {
		document.location.href = fullUrl;
	}	
}

function ajaxDeleteProduct(productName, productId, galleryName)
{
	var q = escape("Oletko varma että haluat poistaa '" + productName + "' ja kaikki siihen liittyvät tiedot?\n\nVAROITUS! Tätä toimintoa ei voi peruuttaa jälkeenpäin.");
	
	if(confirm(unescape(q))) {
		new Ajax.Request("ajax_deleteproduct.php", {
			   method: 'post',
			   postBody: "id="+productId+"&gallery="+galleryName,
			   onComplete: showDeleteProduct
		});
	}
	else {
		return false;
	}
}

function showDeleteProduct(req)
{    
   var res=/false/;
   
   if(!req.responseText.match(res))
   {   	
   		var row = $('row_' + parseInt(req.responseText));
   		if(row) {
   			new Effect.Fade(row);
   		}
   }
   else
   {   		
		document.location.href = document.location.href;
   }
}

function ajaxDeleteFolder(folder)
{
	Effect.Shake($('pics'));
	
	var msg = escape("Oletko varma että haluat poistaa gallerian kaikki kuvat?\n\nVAROITUS! Tätä toimintoa ei voi peruuttaa jälkeenpäin.");
	
	if(confirm(unescape(msg))) {
		new Ajax.Request("ajax_deletepicture.php", {
			   method: "post",
			   postBody: "f="+folder+"&action=deletefolder",
			   onComplete: showDeleteFolderResponse 			   
		});	
	}
	else {
		return false;
	}		
}

function showDeleteFolderResponse(req)
{
   var res=/false/;
       
   if(!req.responseText.match(res))
   {
   		Effect.SwitchOff($('pics'));   		
   		setTimeout('document.location.href = document.location.href;', 1000);
   		
   }
   else
   {
		document.location.href = document.location.href;
   }
}

function ajaxDeleteNews(header, id)
{
	var msg = escape("Oletko varma että haluat poistaa uutisen?\n\n'" + header + "'\n\nVAROITUS! Tätä toimintoa ei voi peruuttaa jälkeenpäin.");
	
	if(confirm(unescape(msg))) {
		new Ajax.Request("ajax_deletenews.php", {
			   method: "post",
			   postBody: "id="+id,
			   onComplete: showDeleteNewsResponse 			   
		});	
	}
	else {
		return false;
	}		
}

function showDeleteNewsResponse(req)
{
   var res=/false/;
       
   if(!req.responseText.match(res))
   {
   		var row = $('row_' + parseInt(req.responseText));
   		if(row) {
   			Effect.Fade(row);   		 		
   		}
   }
   else
   {
		document.location.href = document.location.href;
   }
}

function ajaxDeleteSubCategory(subcategoryid, name)
{
	var msg = escape("Oletko varma että haluat poistaa kategorian\n'" + name + "' ja siihen kuuluvat tuotteet sekä galleriakuvat?\n\nVAROITUS! Tätä toimintoa ei voi peruuttaa jälkeenpäin.");
	
	if(confirm(unescape(msg))) 
	{
		new Ajax.Request("ajax_deletesubcategory.php", {
			   method: "post",
			   postBody: "id="+subcategoryid,
			   onComplete: showDeleteSubCategoryResponse 			   
		});			
   	}
}

function showDeleteSubCategoryResponse(req)
{
   var res=/false/;
       
   if(!req.responseText.match(res))
   {
   		var div = $('div_' + parseInt(req.responseText));
		if(div) {
   			Effect.Puff(div); 
   		}
   }
   else
   {
		document.location.href = document.location.href;
   }
}

function stopclock (){
	if(timerRunning){
		clearTimeout(timerID);
		timerRunning = false;
	}
}

function showtime () {
	var now = new Date();
	var hours = now.getHours();
	var minutes = now.getMinutes();
	var seconds = now.getSeconds()
	if(minutes < 10) minutes="0" + minutes;
	if(seconds < 10) seconds="0" + seconds;
	var timeValue = hours + ":" + minutes + ":" + seconds;

	$("clock").innerHTML = timeValue; 

	timerID = setTimeout("showtime()", 1000);
	timerRunning = true;
}

function startclock() {
	stopclock();
	showtime();
}


function onQuickLink(elm)
{     
   var index = elm.selectedIndex;
   var sel = elm.options[index].value;	
   var nlen  = elm.options[index].value.length;
	
   if((index > 0) && (nlen > 0))
   {
   	  document.location.href = sel;	   	  
   }
   return false;
}