var aURL  = window.location.toString().split("/");
var URL_lang = aURL[3];


function removeElement(element)
{
	element.parentNode.removeChild(element);
	return true;
} 

function swapNodes(item1,item2) {
	// We need a clone of the node we want to swap
	var itemtmp = item1.cloneNode(1);

	// We also need the parentNode of the items we are going to swap.
	var parent = item1.parentNode;

	// First replace the second node with the copy of the first node
	// which returns a the new node
	item2 = parent.replaceChild(itemtmp,item2);

	//Then we need to replace the first node with the new second node
	parent.replaceChild(item2,item1);

	// And finally replace the first item with it's copy so that we
	// still use the old nodes but in the new order. This is the reason
	// we don't need to update our Behaviours since we still have
	// the same nodes.
	parent.replaceChild(item1,itemtmp);

	// Free up some memory, we don't want unused nodes in our document.
	itemtmp = null;
}

// setting cross-browser opacity property
function setOpacity(obj, svalue) {
	obj.style.opacity = svalue/100;
	obj.style.filter = 'alpha(opacity=' + svalue + ')';
	obj = null;
}

function showHide(id) {
	var obj=document.getElementById(id);
	if (obj.style.display=='none')
		obj.style.display='block';
	else if (obj.style.display=='block')
		obj.style.display='none';
}


function hide_text(id) {
	var obj=document.getElementById(id);
	obj.style.display='none'; 
}


function clearMe(me, dit) {
	if(me.value == dit) {
		me.value = "";
		if (dit == "Пароль")
			me.type="password";
	}
}
function fillMe(me, dit){
	if(me.value == "" || me.value == " " || me.value == "  " || me.value == "   ") {
		me.value = dit;
		if (dit == "Пароль")
			me.type="text";
	}
}



function getElementsByClass(searchClass,node,tag) { 	 //Dustin Diaz's getElementsByClass implementation
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		} //if
	} //for
	return classElements;
}
/*
It’s simple. It works just how you think getElementsByClass would work, except better.
   1. Supply a class name as a string.
   2. (optional) Supply a node. This can be obtained by getElementById, or simply by just throwing in “document” (it will be document if don’t supply a node)). It’s mainly useful if you know your parent and you don’t want to loop through the entire D.O.M.
   3. (optional) Limit your results by adding a tagName. Very useful when you’re toggling checkboxes and etcetera. You could just supply “input“. Or, if you’re like me, and you said Good Bye to IE5, you can use the “*” asterisk as a catch-all (meaning ‘any element).
*/

function fgetElementsByClass(searchClass,node,tag) {
	if ( node == null )  node = document;
	if ( tag  == null )  tag = '*';
	if(node.getElementsByClassName) {		// FF3 native implementation
		getResults  = node.getElementsByClassName(searchClass); 
	} else {								// Dustin Diaz's getElementsByClass implementation
		getResults  = getElementsByClass(searchClass, node, tag);
	}
	return getResults;
}


function substr( f_string, f_start, f_length ) {    // Return part of a string
    //      original by: Martijn Wieringa
    if(f_start < 0) {
        f_start += f_string.length;
    }
    if(f_length == undefined) {
        f_length = f_string.length;
    } else if(f_length < 0){
        f_length += f_string.length;
    } else {
        f_length += f_start;
    }
    if(f_length < f_start) {
        f_length = f_start;
    }
    return f_string.substring(f_start, f_length);
}

function strpos( haystack, needle, offset){    // Find position of first occurrence of a string
    //    original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    var i = haystack.indexOf( needle, offset ); // returns -1
    return i >= 0 ? i : false;
}

function shuffle( array ) {    // Shuffle an array
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    for(var j, x, i = array.length; i; j = parseInt(Math.random() * i), x = array[--i], array[i] = array[j], array[j] = x);
    return true;
}





var objMenuOrig; // объект меню - подсвеченная изначально ячейка
var menuTimeout; // просто глобальная переменная
var menuTable;	// таблица, дочерним элементом которой является меню

function menuChangeColorOn(obj) {
	menuTable	 = document.getElementById('menuTable'); objMenuOrig  = fgetElementsByClass('menu_items_selected', menuTable, "TD")[0];

	clearTimeout(menuTimeout);
	var elems = menuTable.getElementsByTagName('td');
	for (var i=0; i<elems.length; i++)
		elems[i].style.backgroundColor = '#38445A';
	objMenuOrig.style.backgroundColor = '#38445A';
	obj.style.backgroundColor		  = '#B41045';
}
function menuChangeColorOut(obj) {
	menuTable	 = document.getElementById('menuTable'); objMenuOrig  = fgetElementsByClass('menu_items_selected', menuTable, "TD")[0];

	menuTimeout = setTimeout(function() {
		obj.style.backgroundColor		  = '';
		objMenuOrig.style.backgroundColor = '#B41045';
	}, 300)
}


function goLink(obj) {
	window.location = obj.lastChild.href;
}

function changeCategory (category) {
	switch (category) {
		case 'photo': {
			document.getElementById("a_photo").style.color = "#FFFFFF";
			document.getElementById("a_video").style.color = "#F273A7";
			document.getElementById("gallery_photo").style.display = "block";
			document.getElementById("gallery_video").style.display = "none";
			document.getElementById("gallery_photo_content").style.display = "block";
			document.getElementById("gallery_video_content").style.display = "none";
			break;
		}
		case 'video': {
			document.getElementById("a_photo").style.color = "#F273A7";
			document.getElementById("a_video").style.color = "#FFFFFF";
			document.getElementById("gallery_photo").style.display = "none";
			document.getElementById("gallery_video").style.display = "block";
			document.getElementById("gallery_photo_content").style.display = "none";
			document.getElementById("gallery_video_content").style.display = "block";
			break;
		}
		
	}
	
}
// changeCategory()



function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
/*
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
*/
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; 
  document.MM_sr=new Array; 
  for(i=0;i<(a.length-2);i+=3)
    if ((x=MM_findObj(a[i]))!=null)
      {
        document.MM_sr[j++]=x; 
        if(!x.oSrc) 
          x.oSrc=x.src; 
        x.src=a[i+2];
      }
}




function newsTicker(obj) {
	var newsObjs = ["anywayanyday", "gaastra", "valars", "audimedcup", "next_venue", "last_news"];
	var aNewsText = [];
	aNewsText['ru'] = {
		"anywayanyday":"<a class='link_lang' href='http://www.anywayanyday.ru/' target='_blank'>anywayanyday</a> - моментальная покупка авиабилетов онлайн и бронирование отелей по всему миру.", 
		"gaastra"     :"<a class='link_lang' href='http://gaastra.ru/' target='_blank'>Gaastra</a> - продажа яхтенной одежды и обуви.",
		"valars"      :"<a class='link_lang' href='http://valars.ru/' target='_blank'>VALARS Group</a> - экспорт зерновых и масличных из России, Украины и Казахстана.",
		"audimedcup"  :"<a class='link_lang' href='http://www.medcup.org/' target='_blank'>Audi MedCup</a> - серия регат мирового уровня.",
		"next_venue"  :"<a class='link_lang' href='http://ru.wikipedia.org/wiki/Кашкайш' target='_blank'>Кашкайш</a> – город и морской порт в Португалии, центр одноимённого муниципалитета в составе округа Лиссабон."
		/*"last_news"  :"<a class='link_lang' href='http://rus7.org/ru/news/' target='_blank'>21 янв 2010</a> – во время подготовки к сезону 2010 года на яхте Valars III был проведен ряд технических доработок."*/
	};
	aNewsText['en'] = {
		"anywayanyday":"<a class='link_lang' href='http://www.anywayanyday.com/' target='_blank'>anywayanyday</a> - online booking and order of airline tickets; booking hotels worldwide.", 
		"gaastra"     :"<a class='link_lang' href='http://gaastra.com/' target='_blank'>Gaastra</a> - sailing sportswear, shoes and other accessories.",
		"valars"      :"<a class='link_lang' href='http://valars.ch/' target='_blank'>VALARS Group</a> - international agricultural trading company comprising its own agricultural and trading subdivisions.",
		"audimedcup"  :"<a class='link_lang' href='http://www.medcup.org/' target='_blank'>Audi MedCup Circuit</a> - the world's leading regatta circuit.",
		"next_venue"  :"<a class='link_lang' href='http://en.wikipedia.org/wiki/Cascais' target='_blank'>Cascais</a> - cosmopolitan suburb of the Portuguese capital and one of the richest municipalities in Portugal."
		/*"last_news"  :"<a class='link_lang' href='http://rus7.org/en/news/' target='_blank'>January 21, 2010</a> – while getting prepared for the 2010 season, Valars III boat underwent a number of modifications."*/
	}; // дата, the, boat.
	var newsText = aNewsText[URL_lang];
	for (objName in appendNewsText)
		//alert(appendNewsText[objName]);
		newsText[objName] = appendNewsText[objName];


	if (obj=="random")
		obj = newsObjs[parseInt(Math.random()*newsObjs.length)];

	_el = $("#newsTickerMove");
	queueLen = _el.queue("fx").length;
	if (_el.css('marginLeft')==$("#newsTicker").css('width')/*queueLen==0*/) {
		_el.html(newsText[obj]);
		_marginScrollOrig = parseInt(_el.css('marginLeft'));
		_marginScrollSet = _marginScrollOrig;
		if (_marginScrollOrig > 0) _marginScrollSet = 0;

		_el.animate({
			marginLeft: _marginScrollSet
		}, 12000, function() {

				tempTimeout = setTimeout(function() {
						_el.animate({
							marginLeft: (0-_marginScrollOrig)
						}, 12000, function() {
								_el.css('marginLeft', _marginScrollOrig);
						});
				}, 2000)

		});
	}
}



$(document).ready(function(){
	$("#edit_index_flash_sign DIV").eq(1).mouseover(function () { 
		newsTicker('next_venue');
	});
	$("#valars_logo").mouseover(function () { 
		newsTicker('valars');
	});
	$("#anywayanyday_logo").mouseover(function () { 
		newsTicker('anywayanyday');
	});
	$("#gaastra_logo").mouseover(function () { 
		newsTicker('gaastra');
	});
	$("#header_red_block").mouseover(function () { 
		newsTicker('last_news');
	});
});


/*
function onLoad() {
// определение переменных перенесено в сами функции, т.к. на момент вызова их, эти переменные еще могут не существовать. 2009,09,28
//	menuTable	 = document.getElementById('menuTable');
//	objMenuOrig  = fgetElementsByClass('menu_items_selected', menuTable, "TD")[0];

	// запускаем countdown счетчик
	// runCountDown();
}
*/


