function go_search(){
	if ($('search_scope').value==1) {
	 url=catsearchhref.replace('__searchstring__', $('search').value);
	 url=url.replace('__cat__', cat_slug);
	}
	else {
	 url=searchhref.replace('__searchstring__', $('search').value);
	 url=url.replace('__cat__', 'visi');
	}
	if (url){
		document.location=url;
	}
}
function on_enter_search(e){
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;
	if (keycode == 13) {
		go_search();
		return false;
	}
	else {
		return true;
	}
}

function on_enter_login(e){
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  else return true;
  if (keycode == 13) {
    go_login();
    return false;
  }
  else {
    return true;
  }
}
function go_login() {
	document.getElementById('id_login_form').submit();
}
function go_logout() {
  new Ajax.Request('/ajax.php?action=logout&sid='+sid, {
    'parameters': {},
    'method': 'POST',
    'onSuccess':function(req){
        document.location='/';
    }
  }
  );
}

function logon_submit(e){
	var keycode='';
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;
	if (keycode == 13) {
		document.login.submit();
		return false;
	}
	else {
		return true;
	}
}
function mk_selectbox(name, options) {
	var sbox=document.createElement('select');
	for (i=0; i<options.length; i++) {
		var sopt=document.createElement('option');
		//sopt.name=options[i].title;
		sopt.value=options[i].value;
		if (options[i]['sel']){
			sopt.selected = true;
		}
		var t=document.createTextNode(options[i].title);
		sopt.appendChild(t);
		sbox.appendChild(sopt);
	}
	sbox.name=name;
	//sbox.addEvent(sbox, 'Change', )
	//	append_child_cat(sbox);
	//}
	sbox.onchange=function() {
		//alert('event go');
		append_child_cat(sbox);
	}
	return sbox;
}
function addEvent(obj, evType, fn, useCapture) {
	var ret=false;
	if(obj!=null){
		if(obj.addEventListener){
			obj.addEventListener(evType,fn,useCapture);
			ret=true;
		}
		else if(obj.attachEvent){
			obj.attachEvent('on'+evType,fn);
			ret=true;
		}
	}
	return ret;
}
function isValidEmail(str) {
	apos=str.indexOf("@");
	dotpos=str.lastIndexOf(".");
	if (apos<1||dotpos-apos<2) {
		return false;
	}
	else {
		return true;
	}
}
function isValidPhone(str) {
  if (str.length < 8) {
    return false;
  }
  else {
    return true;
  }
}
function isValidTextBody(str) {
  if (!str.length) return true;
  var reg= new RegExp("(http://|www.)", 'i');
  if (reg.test(str)) {
    return false;
  }
  return true;
}
function add_to_favourites(id) {
  new Ajax.Request('/ajax.php?action=add_to_favourites&sid='+sid+'&id='+id, {
                  onSuccess: function(transport) {
                     var com=transport.responseText;
                     eval(com);
                    }
                  });
}
function absPosition(obj) {
      var x = y = 0;
      while(obj) {
            x += obj.offsetLeft;
            y += obj.offsetTop;
            obj = obj.offsetParent;
      }
      return {x:x, y:y};
}


var flag=false;
var shift_x;
var shift_y;

function start_drag(itemToMove,e){
	if(!e) e = window.event;
	flag=true;
	shift_x = e.clientX-parseInt(itemToMove.style.left);
	shift_y = e.clientY-parseInt(itemToMove.style.top);

	if(e.stopPropagation) e.stopPropagation();
	else e.cancelBubble = true;
	if(e.preventDefault) e.preventDefault();
	else e.returnValue = false;
}

function end_drag(){ flag=false; }

function dragIt(itemToMove,e){
	if(!flag) return;
	if(!e) e = window.event;
	itemToMove.style.left = (e.clientX-shift_x) + "px";
	itemToMove.style.top = (e.clientY-shift_y) + "px";

	if(e.stopPropagation) e.stopPropagation();
	else e.cancelBubble = true;
	if(e.preventDefault) e.preventDefault();
	else e.returnValue = false;
}
function setHomePage() {
  try {
	  //var newdiv = document.createElement('div');
	  //newdiv.setAttribute('id', 'divblock');
	  //newdiv.id='divblock';
	  //document.getElementById('container').appendChild(newdiv);
	  //document.getElementById('divblock').style.behavior='url(#default#homepage)';
	  //document.getElementById('divblock.').setHomePage('http://www.tavavieta.lv');
	  document.getElementById('start_link').style.behavior='url(#default#homepage)';
	  document.getElementById('start_link').setHomePage('http://www.tavavieta.lv');
  }
  catch (err) {
    //alert('Atvajnojet, bet tas links strāda tikai ar Internet Explorer 7');
    alert('Ar jūsu pārluka versiju vajag izvēlēt mājas lapu ar rokām. Atvainojamies par neērtību.');
  }
}
function get_interview_front(id) {
  new Ajax.Updater('interview_front_container', '/ajax.php?action=get_interview_front&id='+id, {});
}
function insertSmile(id, elm_id){
  var obj = document.getElementById(elm_id);
  if(typeof(document.selection)!='undefined') {
    obj.focus();
    var range = document.selection.createRange();
    if(range.parentElement() != obj) {
      return false;
    }
    var orig = obj.value.replace(/rn/g, "n");
    range.text = id;

    var actual = tmp = obj.value.replace(/rn/g, "n");
    for(var diff = 0; diff < orig.length; diff++) {
      if(orig.charAt(diff) != actual.charAt(diff)) break;
    }
    for(var index = 0, start = 0; (tmp = tmp.replace(id, "")) && (index <= diff); index = start + id.length) {
      start = actual.indexOf(id, index);
    }
  }
  else {
    var startPos = obj.selectionStart;
    var endPos = obj.selectionEnd;
    obj.value = obj.value.substr(0, startPos) + id + obj.value.substr(endPos, obj.value.length);
  }
  obj.focus();
  //document.getElementById('smiles_container').style.display='none';
}
function setBannerCookie( name, cokie_expire ){
	var expire = new Date();
	expire.setTime( expire.getTime() + parseInt(cokie_expire) );
	var str = "banner_showed_" + name + "_=1; expires=" + expire.toGMTString() + "; path=/";
	document.cookie = str;
}

function getBannerCookie( name ) {
	var prefix = "banner_showed_" + name + "_=";
	var begin = document.cookie.indexOf( "; " + prefix );
	if ( begin == -1 ) {
		begin = document.cookie.indexOf( prefix );
		if ( begin != 0 ) {
			return false;
		}
	} else {
		begin += 2;
	}
	var end = document.cookie.indexOf( ";", begin );
	if (end == -1){
		end = document.cookie.length;
	}
	var result = unescape(document.cookie.substring(begin + prefix.length, end));
	return result;
}

function checkBrowser(){
	this.ver=navigator.appVersion
	this.dom=document.getElementById?1:0
	this.ie6=((navigator.appName.indexOf("Microsoft")!=-1 || this.ver.indexOf("MSIE 6")>-1) && this.dom)?1:0;
	this.ie5=((navigator.appName.indexOf("Microsoft")!=-1 || this.ver.indexOf("MSIE 5")>-1) && this.dom)?1:0;
	this.ie4=(document.all && !this.dom)?1:0;
	this.ns5=(this.dom && parseInt(this.ver) >= 5) ?1:0;
	this.ns4=(document.layers && !this.dom)?1:0;
	this.gecko=(navigator.userAgent.indexOf("Gecko")!=-1)?1:0;
	this.mac=((navigator.appName.indexOf("Mac")!=-1 || this.ver.indexOf("Mac")>-1) && this.dom)?1:0;

    var test_cookie = setBannerCookie( 'test_cookie', 5 * 1000 );
    this.cookie=getBannerCookie( 'test_cookie' )?1:0;

	return this
}
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

/* Scrolling banner */
var scrollingStepPx = 1;
var scrollingStepMs = 50;
var scrollingInterval;

function scrollingStart(bannerSrc,bannerName,bannerId,width,height){
    var browser = checkBrowser();
    var scrollingShowed = false;
    var scrollingShowed = getBannerCookie( bannerName );
    
    /*( !scrollingShowed && ( browser.ie5 || browser.ie6 ) && browser.dom && 1==1 ){ */
    if ( !scrollingShowed )
    {
        var cookieExpire = 12 * 60 * 60 * 1000;
        var bust = Math.floor(89999999*Math.random()+10000000);
        var millis = new Date().getTime();            
        
        // izveidojam ifreimu, anchoru un img objektus ar visiem parametriem
        var scrollingIframe = document.createElement('iframe');
        scrollingIframe.setAttribute('src', scroll_banner_src);
        scrollingIframe.setAttribute('id', bannerName);
        scrollingIframe.setAttribute('marginwidth','0');
        scrollingIframe.setAttribute('marginheight','0');
        scrollingIframe.setAttribute('width','1');
        scrollingIframe.setAttribute('height','1');
        var scrollingA = document.createElement('a');
        scrollingA.setAttribute('href', scroll_banner_href);
        scrollingA.setAttribute('left', '0px');
        scrollingA.style.position='relative';
        scrollingA.setAttribute('target', scroll_banner_target);
        var scrollingImg = document.createElement('img');
        scrollingImg.setAttribute('src',bannerSrc);
        scrollingImg.setAttribute('alt','ClickHere!');
        scrollingImg.setAttribute('width',width);
        scrollingImg.setAttribute('height',height);
        scrollingImg.setAttribute('left', '0px');
        
        // ievietojam izveidotos objektus scrolling-content div elementaa
        var scrollingContent = document.getElementById('scrolling-content');
        scrollingImgA = scrollingImg.cloneNode(true);
        scrollingImgB = scrollingImg.cloneNode(true);
        scrollingA.appendChild(scrollingImg);
        scrollingA.appendChild(scrollingImgA);
        scrollingA.appendChild(scrollingImgB);
        scrollingA.style.width = width * 3 + 5 + 'px';
        scrollingA.style.height = height + 'px';
        scrollingContent.appendChild(scrollingA);
        //scrollingContent.appendChild(scrollingIframe);
        // uzliekam scrolling-contentam augstumu platumu un poziiciju
        scrollingContent.style.width = width * 3 + 5 + 'px';
        scrollingContent.style.height = height + 'px';
        scrollingContent.style.left = '0px';
        scrollingContent.style.top = '0px';

        // uztaisam bannera aizveershanas pogu
        var scrolling = document.getElementById('scrolling-banner');
        var button = document.createElement( "a" );
	    button.className = "hide-banner";
	    button.setAttribute( "cookieexpire", cookieExpire );
        button.setAttribute( "bannername", bannerName );
	    button.onclick = function()
        {
          setBannerCookie(this.getAttribute('bannername'), this.getAttribute('cookieexpire') )
          scrollingStop();
        }
	    var buttonText = document.createTextNode( "" );
	    buttonText.nodeValue = "Slēpt šo reklāmu";
	    button.appendChild( buttonText );
	    scrolling.appendChild( button );
	    
        scrolling.style.left = "0px";
        if ( document.all )
        { 
		    // ie
            scrolling.style.top = ( document.documentElement.scrollTop + document.documentElement.clientHeight - height ) + "px";
        }
	    else
        {
		    // paareejiem browseriem
            scrolling.style.top = ( window.innerHeight - height ) + "px";
        }
	    scrolling.style.width = document.body.clientWidth + "px";
        scrolling.style.height = height + 'px';
        if ( window.attachEvent ) 
        {
		    window.attachEvent( "onscroll", scrollingRePosition );
		    window.attachEvent( "onresize", scrollingRePosition );
	    } 
        else 
        {
		    window.addEventListener( "resize", scrollingRePosition, 1 );
	    }
	    scrolling.style.visibility = 'visible';
        scrollingInterval = setInterval( "scrollingMove(" + width + ")", scrollingStepMs );
        
	    //setBannerCookie( bannerName, cookieExpire );
    }

}
function scrollingRePosition(){
    var scrolling = document.getElementById('scrolling-banner');
    var height = parseInt(scrolling.style.height);   
    
    // nochekojam vai sestais jo sestajam gljuks
    var agt=navigator.userAgent.toLowerCase();
    var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
    var is_ie6 = (is_ie && (agt.indexOf("msie 6.")!=-1) );
    if (is_ie6)
    {
        scrolling.style.top = ( document.documentElement.scrollTop + document.documentElement.clientHeight - height ) + "px"; //ie6
    }
    else if (document.all)
    {
        scrolling.style.top = document.documentElement.clientHeight - height +"px"; // ie7
    }
    else
    {
        scrolling.style.top = ( window.innerHeight - height ) + "px"; //other
    }   
	scrolling.style.width = document.body.clientWidth + "px";
}
function scrollingMove(width) {
	var scrollingContent = document.getElementById( 'scrolling-content' );
	var scrollingContentPosition = parseInt( scrollingContent.style.left );
	scrollingContent.style.left = scrollingContentPosition - scrollingStepPx + 'px';
	if ( Math.abs(scrollingContentPosition) >= width ) {
		scrollingContent.style.left = ( - scrollingStepPx ) + 'px';
	}
}
function scrollingStop() {
	var scrolling = document.getElementById( 'scrolling-banner' );
	scrolling.style.visibility = 'hidden';
	clearInterval(scrollingInterval);
}
function openUrl_banner(url){
    window.location=url;
}
function popupMessage(recipient_id){
	var popMWin = window.open('/new_message/' + recipient_id + '/', 'popupMessage', 'width=550,height=300');
	popMWin.focus();
	return false;
}
function popupForum(){
	var popFWin = window.open('/frm_new_forum/', 'popupForum', 'width=550,height=300,top=100,left=200');
	popFWin.focus();
	return false;
}
function init_friendship_request(id){
	new Ajax.Updater('friendship_request_form', '/ajax.php?action=init_friendship_request&id=' + id, {
		'onComplete': function(transport){
				document.getElementById('friendship_request_form').style.display='';
			}
	});
}
function friendship_request_confirm(id){
	new Ajax.Request('/ajax.php?action=friendship_request_confirm&id=' + id, {
		'onComplete': function(transport){
			hide_friendship_request();
	}
	});
}
function hide_friendship_request(){
	$('friendship_request_form').style.display='none';
}
