// Removes leading whitespaces
function LTrim( value )
{
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value )
{
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value )
{
	return LTrim(RTrim(value));
	
}

function preloadImages(img_array)
{
	pics_array = img_array.split(',');
	for(i = 0; i < pics_array.length; i++)
	{
		eval("c"+i+" = new Image; c"+i+".src = pics_array[i];");
	}
}

function change_class(tid, cfg)
{
	if(cfg == 1) newclass = 'admin_button';
	else if(cfg == 2) newclass = 'admin_button_over';
	
	//var dtarget = document.getElementById(tid);
	
	tid.className = newclass;
}

Array.prototype.in_array = function ( obj )
{
	var len = this.length;
	for ( var x = 0 ; x <= len ; x++ )
	{
		if ( this[x] == obj ) return true;
	}
	return false;
}

function valid_email(email)
{
	var chk = /^[^@]{1,64}@[^@]{1,255}$/g;
	if ( !email.match ( chk ) )
	{
		return false;
	}
	
	email_array = email.split("@");
	local_array = email_array[0].split(".");
	for (var i = 0; i < local_array.length; i++)
	{
		var chk = /^(([A-Za-z0-9!#$%&#038;'*+/=?^_`{|}~-][A-Za-z0-9!#$%&#038;'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/g;
		if ( !local_array[i].match ( chk ) )
		{ 
			return false;
		}
	}
	
	var chk = /^\[?[0-9\.]+\]?$/g;
	if ( !email_array[1].match ( chk ) )
	{
		domain_array = email_array[1].split(".");
		if(domain_array.length < 2) return false;
		for (var i = 0; i < domain_array.length; i++)
		{
			if(domain_array[i].length < 2) return false;
			
			var chk = /^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/g;
			if ( !domain_array[i].match ( chk ) ) return false;
		}
	}
	return true;
}

function checkForm(formname, fields_array, errors_array)
{
	eval("var reg = document." + formname + ";");
	
	for(var i = 0; i < fields_array.length; i++)
	{
		eval("var curr_field = reg." + fields_array[i] + ";");
		
		if(trim(curr_field.value) == '')
		{
			curr_field.focus();
			showLightboxAlert(errors_array[i], 'Warning', 'document.' + formname + '.' + fields_array[i] + '.focus();');
			return false;
		}
	}
	reg.submit();
}

function setHomepage(what)
{
	if (document.all)
	{
		what.style.behavior='url(#default#homepage)';
		what.setHomePage('http://www.compote-collective.com/');
	}
	else if (window.sidebar)
	{
		if(window.netscape)
		{
			try
			{
				netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
			}  
			catch(e)
			{
				var msg = "Това действие е забранено от Вашия браузер. Ако искате да го активирате, моля въведете 'about:config' в адресната линия, и сменете стойноста на 'signed.applets.codebase_principal_support' на 'true'";
				showLightboxAlert(msg, 'Warning', '');
			}
		}
	}
}

function addToFavorites(url, title)
{
	// Mozilla Firefox Bookmark
	if ( window.sidebar )
	{
		window.sidebar.addPanel(title, url, "");
	}
	// IE Favorite
	else if( window.external )
	{
		window.external.AddFavorite( url, title);
	}
	// Opera Hotlist
	else if( window.opera && window.print )
	{
		//Opera Hotlist
    obj.setAttribute('href', url);
    obj.setAttribute('title', title);
    obj.setAttribute('rel', 'sidebar');
    obj.click();
    return false;
	}
}

function submitOnEnter(myfield, submit_function, e)
{
	var keycode;
	
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;
	
	if (keycode == 13)
	{
		eval(submit_function);
		return false;
	}
	else return true;
}

function IsImageOk(img)
{
	if(!img.complete)
	{
		return false;
	}
	
	if(typeof img.naturalWidth != "undefined" && img.naturalWidth == 0)
	{
		return false;
	}
	
	return true;
}

function closeBox(eval_script)
{
	if(document.getElementById('showMessage')) 
	{
		document.body.removeChild(document.getElementById('showMessage'));
		document.body.removeChild(document.getElementById('showMessageBox'));
		
		eval(eval_script);
		
		//enable scroll
		var elementBody = document.getElementsByTagName('html');
		elementBody[0].style.overflow = '';
		elementBody[0].onselectstart = function() {return true;};
	}
}

function showLightboxAlert(msg, msg_title, eval_script)
{
	var sizes = getPageSize();
	var scrollWidth = getScrollX();
	var scrollHeight = getScrollY();
	var windowWidth = winWidth();
	var windowHeight = winHeight();
	var bodyHeight = getPageSize();
	
	//main div
	dl = document.createElement('div');
	dl.id = 'showMessage';
	dl.style.position = 'absolute';
	dl.style.width = '100%';
	dl.style.height = bodyHeight[1] + 'px';
	dl.style.backgroundColor = '#000000';
	dl.style.top = 0+'px';
	dl.style.left = scrollWidth+'px';
	dl.style.textAlign = 'center';
	dl.style.filter='alpha(opacity=70)';
	dl.style.opacity='.70';
	dl.style.zIndex = 1000;
	
	//msg div
	pl = document.createElement('div');
	pl.id = 'showMessageBox';
	pl.style.width = '300px';
	pl.style.position = 'absolute';
	pl.style.backgroundColor = '#FFFFFF';
	pl.style.top = ((windowHeight/2)+scrollHeight)-100+'px';
	pl.style.left = '50%';
	pl.style.marginLeft = '-150px';
	pl.style.padding = '0px';
	pl.style.textAlign = 'left';
	pl.style.border = '#444446 1px solid';
	pl.style.zIndex = 1001;
	
	//close div
	cl = document.createElement('div');
	cl.id = 'showMessageBoxClose';
	cl.className = 'alert_bottom';
	cl.innerHTML = '<input type="button" class="input-btn" onfocus="this.blur();" onclick="closeBox(\'' + eval_script + '\');" value="Close"/>';
	//cl.innerHTML = '<input type="button" onclick="javascript:closeBox(\'' + eval_script + '\');" class="input-btn" value="Затвори"/>';
	
	pl.innerHTML = '<div class="alert_top"><b>' + msg_title + '</b></div>';
	pl.innerHTML += '<div class="alert_holder">' + msg + '</div>';
	pl.appendChild(cl);
	
	document.body.insertBefore(dl, document.body.firstChild);
	document.body.insertBefore(pl, document.body.firstChild);
	
	//disable scroll
	var elementBody = document.getElementsByTagName('html');
	elementBody[0].style.overflow = 'hidden';
	elementBody[0].onselectstart = function() {return false;};
}

function showBigBox(targetURL, twidth, theight, txt)
{
	//opera fix
	var agt = navigator.userAgent.toLowerCase();
  var is_opera = (agt.indexOf("opera") != -1);
	//if(is_opera) txt = url.decode(txt);
	
	var sizes = getPageSize();
	var scrollWidth = getScrollX();
	var scrollHeight = getScrollY();
	var windowWidth = winWidth();
	var windowHeight = winHeight();
	var bodyHeight = getPageSize();
	
	//main div
	dl = document.createElement('div');
	dl.id = 'showMessage';
	dl.style.position = 'absolute';
	dl.style.width = '100%';
	//dl.style.height = parseInt(document.getElementById('allover').offsetHeight) + 40 + 'px';
	dl.style.height = bodyHeight[1] + 'px';
	dl.style.backgroundColor = '#000000';
	dl.style.top = 0+'px';
	//dl.style.top = scrollHeight+'px';
	dl.style.left = scrollWidth+'px';
	dl.style.textAlign = 'center';
	dl.style.filter='alpha(opacity=70)';
	dl.style.opacity='.70';
	dl.style.zIndex = 1000;
	
	//content div
	pl = document.createElement('div');
	pl.id = 'showMessageBox';
	pl.style.cssText = 'float:left;';
	pl.style.position = 'absolute';
	pl.style.backgroundColor = '#FFFFFF';
	pl.style.top = ((windowHeight/2)+scrollHeight)-250+'px';
	pl.style.left = '50%';
	pl.style.marginLeft = '-' + (twidth + 3)/2 +'px';
	pl.style.padding = '10px 5px 10px 14px';
	pl.style.width = twidth + 3 + 'px';
	//pl.style.height = theight + 45 + 'px';
	pl.style.textAlign = 'center';
	pl.style.zIndex = 1001;
	pl.style.backgroundImage = 'url(\'http://www.compote-collective.com/images/default/spinner.gif\')';
	pl.style.backgroundPosition = 'center';
	pl.style.backgroundRepeat = 'no-repeat';
	
	//close div
	cl = document.createElement('div');
	cl.id = 'showBoxContentClose';
	cl.style.cssText = 'float:left;';
	cl.style.width = twidth + 7 + 'px';
	//cl.style.border = 'red 1px solid';
	cl.style.backgroundColor = '#FFFFFF';
	cl.style.textAlign = 'left';
	cl.style.padding = '10px 0px 10px 0px';
	cl_in = '<div style="float:left;padding-left:5px;width:' + (twidth - 105) + 'px;font-size:12px;">' + txt + '</div>';
	cl_in += '<div style="float:right;width:90px;text-align:left;"><a href="javascript:closeBox(\'\');" style="text-decoration:none;color:#666666;white-spacing:nowrap;">Затвори <img src="http://www.compote-collective.com/images/default/close.gif" alt="Затвори" style="vertical-align:middle;border:0px;"/></a></div>';
	cl.innerHTML = cl_in;
	
	//content
	content_div = document.createElement('div');
	content_div.style.cssText = 'float:left;';
	content_div.style.width = twidth + 'px';
	//content_div.style.height = theight + 'px';
	content_div.id = 'contentBox';
	
	pl.appendChild(content_div);
	pl.appendChild(cl);
	
	var pars = '';
	new Ajax.Updater('contentBox', targetURL, {method:'get', postBody:pars, evalScripts:true});
	
	document.body.insertBefore(dl, document.body.firstChild);
	document.body.insertBefore(pl, document.body.firstChild);
	
	//var elementBody = document.getElementsByTagName('html');
	//elementBody[0].style.overflow = 'hidden';
	//elementBody[0].onselectstart = function() {return false;};
}

function ExtractNumber(value)
{
	var n = parseInt(value);
	return n == null || isNaN(n) ? 0 : n;
}

function Set_Cookie( name, value, expires, path, domain, secure ) 
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

// this function gets the cookie, if it exists
function Get_Cookie( name )
{
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	
	if ( ( !start ) &&
	( name != document.cookie.substring( 0, name.length ) ) )
	{
		return null;
	}
	
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	
	return unescape( document.cookie.substring( len, end ) );
}

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowW, windowH;
	if (self.innerHeight) {	// all except Explorer
		windowW = self.innerWidth;
		windowH = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowW = document.documentElement.clientWidth;
		windowH = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowW = document.body.clientWidth;
		windowH = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowH){
		pageHeight = windowH;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowW){	
		pageWidth = windowW;
	} else {
		pageWidth = xScroll;
	}
	
	arrayPageSize = new Array(pageWidth,pageHeight,windowW,windowH) 
	return arrayPageSize;
}

function winWidth()
{
  var myWidth = 0;
  if( typeof( window.innerWidth ) == 'number' )
  {
    //Non-IE
    myWidth = window.innerWidth;
  }
  else if( document.documentElement && document.documentElement.clientWidth )
  {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
  }
  else if( document.body && document.body.clientWidth )
  {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
  }
  return myWidth;
}

function winHeight()
{
  var myHeight = 0;
  if( typeof( window.innerHeight ) == 'number' )
  {
    //Non-IE
    myHeight = window.innerHeight;
  }
  else if( document.documentElement && document.documentElement.clientHeight )
  {
    //IE 6+ in 'standards compliant mode'
    myHeight = document.documentElement.clientHeight;
  }
  else if( document.body && document.body.clientHeight )
  {
    //IE 4 compatible
    myHeight = document.body.clientHeight;
  }
  return myHeight;
}

function getScrollY()
{
  var scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' )
 	{
    //Netscape compliant
    scrOfY = window.pageYOffset;
  }
  else if( document.body && document.body.scrollTop )
  {
    //DOM compliant
    scrOfY = document.body.scrollTop;
  }
  else if( document.documentElement && document.documentElement.scrollTop )
  {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
  }
  return scrOfY;
}

function getScrollY()
{
  var scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' )
 	{
    //Netscape compliant
    scrOfY = window.pageYOffset;
  }
  else if( document.body && document.body.scrollTop )
  {
    //DOM compliant
    scrOfY = document.body.scrollTop;
  }
  else if( document.documentElement && document.documentElement.scrollTop )
  {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
  }
  return scrOfY;
}

function getScrollX()
{
  var scrOfX = 0;
  if( typeof( window.pageXOffset ) == 'number' )
 	{
    //Netscape compliant
    scrOfX = window.pageXOffset;
  }
  else if( document.body && document.body.scrollLeft )
  {
    //DOM compliant
    scrOfX = document.body.scrollLeft;
  }
  else if( document.documentElement && document.documentElement.scrollLeft )
  {
    //IE6 standards compliant mode
    scrOfX = document.documentElement.scrollLeft;
  }
  return scrOfX;
}

function fixContactFromEmail(what)
{
	if(trim(what.value) == 'your@email.here') what.value = '';
	else if(trim(what.value) == '') what.value = 'your@email.here';
}

function fixContactSubject(what)
{
	if(trim(what.value) == 'subject here') what.value = '';
	else if(trim(what.value) == '') what.value = 'subject here';
}

function checkContactsForm()
{
	var reg = document.contactsform;
	
	if(trim(reg.to_email.value) == '')
	{
		reg.to_email.focus();
		showLightboxAlert('Choose contact e-mail address.', 'Attention', 'document.contactsform.to_email.focus();');
		return false;
	}
	else if(trim(reg.from_email.value) == '' || trim(reg.from_email.value) == 'your@email.here')
	{
		reg.from_email.focus();
		showLightboxAlert('Enter Your e-mail address.', 'Attention', 'document.contactsform.from_email.focus();');
		return false;
	}
	else if(!valid_email(trim(reg.from_email.value)))
	{
		showLightboxAlert('Enter valid e-mail address.', 'Attention', 'document.contactsform.from_email.focus();');
		return false;
	}
	else if(trim(reg.subject.value) == '' || trim(reg.subject.value) == 'subject here')
	{
		reg.from_email.focus();
		showLightboxAlert('Enter Your subject.', 'Attention', 'document.contactsform.subject.focus();');
		return false;
	}
	else if(trim(reg.text.value) == '')
	{
		reg.text.focus();
		showLightboxAlert('Enter Your text.', 'Attention', 'document.contactsform.text.focus();');
		return false;
	}
	
	reg.submit();
}

var dntrmv = 0;
function showThumbInfo(project_id, project_name, project_type, project_artist)
{
	if(!document.getElementById('thumbinfo' + project_id))
	{
		var aim = new Image();
		aim.src = 'http://www.compote-collective.com/images/default/cp_blue_arrow.gif';
		
		var tidiv_holder = document.createElement('div');
		tidiv_holder.id = 'thumbinfo_holder' + project_id;
		tidiv_holder.className = 'thumb_info_holder';
		tidiv_holder.style.marginTop = -126 + 'px';
		tidiv_holder.style.marginLeft = -1 + 'px';
		tidiv_holder.onmouseout = function() { if(dntrmv == 0) hideThumbInfo(project_id); };
		
		var tidiv = document.createElement('div');
		tidiv.id = 'thumbinfo' + project_id;
		tidiv.className = 'thumb_info';
		tidiv.innerHTML = project_artist + '<br/>' + project_name + '<br/>' + project_type;
		
		var tidiv_image = document.createElement('div');
		tidiv_image.id = 'thumbinfo_image' + project_id;
		tidiv_image.className = 'thumb_info_image';
		tidiv_image.onmouseover = function() { dntrmv = 1; };
		tidiv_image.onmouseout = function() { dntrmv = 0; };
		tidiv_image.innerHTML = '<a href="http://www.compote-collective.com/project/'+project_id+'/'+escape(project_name)+'.htm" title="view details"><img src="http://www.compote-collective.com/images/default/cp_blue_arrow.gif" alt="view details" class="blue_arrow"/></a>';
		
		document.getElementById('thumb' + project_id).appendChild(tidiv);
		document.getElementById('thumb' + project_id).appendChild(tidiv_holder);
		document.getElementById('thumb' + project_id).appendChild(tidiv_image);
	}
}

function hideThumbInfo(project_id)
{
	if(document.getElementById('thumb' + project_id))
	{
		dntrmv = 0;
		
		if(document.getElementById('thumbinfo_holder' + project_id))
		{
			document.getElementById('thumb' + project_id).removeChild(document.getElementById('thumbinfo_holder' + project_id));
		}
		if(document.getElementById('thumbinfo' + project_id))
		{
			document.getElementById('thumb' + project_id).removeChild(document.getElementById('thumbinfo' + project_id));
		}
		if(document.getElementById('thumbinfo_image' + project_id))
		{
			document.getElementById('thumb' + project_id).removeChild(document.getElementById('thumbinfo_image' + project_id));
		}
	}
}

function checkIllustrationsForm(formname, fields_array, errors_array)
{
	eval("var reg = document." + formname + ";");
	
	for(var i = 0; i < fields_array.length; i++)
	{
		eval("var curr_field = reg." + fields_array[i] + ";");
		
		if(trim(curr_field.value) == '')
		{
			curr_field.focus();
			showLightboxAlert(errors_array[i], 'Warning', 'document.' + formname + '.' + fields_array[i] + '.focus();');
			return false;
		}
	}
	
	if(reg.pics_count.value == 1 && trim(reg.pic_1.value) == '')
	{
		showLightboxAlert('Please, browse for at least one pic.', 'Warning', 'document.' + formname + '.pic_1.focus();');
		return false;
	}
	
	reg.submit();
}

function setIllustrationPicFields(formname)
{
	eval("var reg = document." + formname + ";");
	
	var cpc = reg.pics_count.value;
	var npc = cpc + 1;
	
	reg.pics_count.value = npc;
	
	var dtp = document.getElementById('pics_fields');
	
	var npf = document.createElement('input');
	npf.name = 'pic_' + npc;
	npf.className = 't1';
	npf.setAttribute('type','file');
	npf.style.marginTop = 5 + 'px';
	npf.value = '';
	npf.onchange = function(){
			setIllustrationPicFields(formname);
		};
	
	eval("reg.pic_" + cpc + ".onchange = function(){ return false; };");
	
	dtp.appendChild(npf);
}

function convertWord(type, content)
{
	switch (type)
	{
		// Gets executed before the built in logic performes it's cleanups
		case "before":
		// do nothing
		break;
		
		// Gets executed after the built in logic performes it's cleanups
		case "after":
		content = content.replace(/<(!--)([\s\S]*)(--)>/gi, "");
		break;
	}
	
	return content;
}
