//------------------------------------------------------
//------------------START AJAX--------------------------
//------------------------------------------------------
 
var httpRequest;
var requestTimeout;
var clearMessageTimeout;
var url;

function createHttpRequest() {
	httpRequest = null;
    if (window.XMLHttpRequest) {
        try {
            httpRequest = new XMLHttpRequest();
        } catch (e){}
    } else if (window.ActiveXObject) {
        try {
            httpRequest = new ActiveXObject('Msxml2.XMLHTTP');
        } catch (e){
            try {
                httpRequest = new ActiveXObject('Microsoft.XMLHTTP');
            } catch (e){
            	httpRequest = null;
            }
        }
    }
    
    return httpRequest;
}
 
function loadXMLDoc(url) {

	httpRequest = createHttpRequest();
	
    if (httpRequest) {
        httpRequest.onreadystatechange = processReqChange;
        httpRequest.open("GET", url, true);
        httpRequest.send(null);
        requestTimeout = setTimeout("httpRequest.abort();", 5000);
    } else {
        alert("Браузер не поддерживает AJAX");
    }
}

function getSiteName( url_obj )
{
	var url = ''; url += url_obj;
   	firstIndex = url.indexOf( 'http://' );
   	if ( -1 != firstIndex )
   	{
   		firstIndex = 7;
   		url_part = url.slice( firstIndex, url.length );
   		lastIndex = url_part.indexOf("/");
   		firstIndex = 0;
   		siteName = url_part.slice( firstIndex, lastIndex );
   		
   		return siteName;
   	}
   	else
   	{
   		alert( 'передано неверное значение url' );
   	}
}


function processReqChange() {

    if (httpRequest.readyState == 4) {
        //clearTimeout(requestTimeout);
        // only if "OK"
        if (httpRequest.status == 200) {
            response=httpRequest.responseText;
   			document.getElementById('recievedMessage').innerHTML = response;
   			clearMessageTimeout = setTimeout("document.getElementById('recievedMessage').innerHTML='';", 1000);
        } else {
            //alert("Не удалось получить данные\n");
        }
    }  
}

//---------------------------------------------------------------------------------
// Работа с модулем рекламы
//---------------------------------------------------------------------------------

/*
 * Обработка клика на баннере
 */
function increaseClickCount(advertisment_id) {
 	siteName = getSiteName( document.location );
   	url = "http://" + siteName + "/ajax/advertisment/increase_clicks_count/" + advertisment_id;
   	loadXMLDoc(url);

   	clearTimeout(clearMessageTimeout);
}

function resetClicksCount(advertisment_id) {
 	siteName = getSiteName( document.location );
   	url = "http://" + siteName + "/ajax/advertisment/reset_clicks_count/" + advertisment_id;
   	loadXMLDoc(url);
    
    clearTimeout(clearMessageTimeout);
    
    document.getElementById('clicks_count_' + advertisment_id).innerHTML = '0';
}

//---------------------------------------------------------------------------------
// Работа с голосованием
//---------------------------------------------------------------------------------

/**
 * Пользователь сделал выбор
 */
 
 function SetChoice( competition_item_id )
 {
 	competition_alias = document.getElementById('competition_alias').value;
 	prev_user_choice_elem = document.getElementById('prev_user_choice');
 	prev_user_choice = document.getElementById('prev_user_choice').value;
 	
 	siteName = getSiteName( document.location );
   	url = "http://" + siteName + "/ajax/konkurs/ratings/set/" + competition_item_id;
   	loadXMLDoc(url);

   	clearTimeout(clearMessageTimeout);
   	
   	// заменяем содержимое
   	rating_box_elem_id = 'rating_box_' + competition_item_id;

   	document.getElementById( rating_box_elem_id ).innerHTML = "<div class=\"voited\">Спасибо, ваш голос учтен!<br /><a class=\"item_title_link\" href=\"/konkurs/" + competition_alias+ "/result\">Просмотреть результаты</a></div>";

   	if ( 'false' != prev_user_choice && '' != prev_user_choice ) {
   		prev_rating_box_elem_id = 'rating_box_' + prev_user_choice;
   		if ( document.getElementById( prev_rating_box_elem_id ) ) {
   			 document.getElementById( prev_rating_box_elem_id ).innerHTML = "<a class=\"set_choice\" style=\"text-decoration: none;\" href=\"javascript:void(0);\" onclick=\"SetChoice('" + prev_user_choice + "')\"><img style=\"border: 0; text-decoration: none; color:white\" src=\"/images/competitions/golos.png\" title=\"Проголосовать\" alt=\"Проголосовать\" /></a>"
   		}
	}
   	prev_user_choice_elem.value = competition_item_id;
 }

//---------------------------------------------------------------------------------
// Работа с модулем рейтингов
//---------------------------------------------------------------------------------

/**
 * Работа с рейтингами в виде радио кнопок
 */
 
 function SetRating(radioID, radioGroup)
 {
 	rating = radioID.value;
 	sourceID = document.getElementById('rating_data').value;
 	moduleID = document.getElementById('rating_module').value;
	if(!radioGroup) {
		return;
	}
	if(radioGroup == undefined) {
		radioGroup.checked = (radioGroup.value == rating);
		return;
	}

 	for(i = 0; i < radioGroup.length; i++) {
 		radioGroup[i].checked = false;
 		if(radioGroup[i].value == rating) {
			radioGroup[i].checked = true;
		}
 	}
 	siteName = getSiteName( document.location );
   	url = "http://" + siteName + "/ajax/ratings/add/" + sourceID + "/" + moduleID + "/" + rating;
   	loadXMLDoc(url);

   	clearTimeout(clearMessageTimeout);
 }

//----------------------------------------
//
//
// Ниже секция вспомагательных методов
// Перенести ее в отдельный файл
//
//----------------------------------------

function randomNumber (m,n)
{
  m = parseInt(m);
  n = parseInt(n);
  return Math.floor( Math.random() * (n - m + 1) ) + m;
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
/*  SHA-1 implementation in JavaScript (c) Chris Veness 2002-2009                                 */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

function sha1Hash(msg)
{
    // constants [§4.2.1]
    var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];


    // PREPROCESSING

    msg += String.fromCharCode(0x80); // add trailing '1' bit (+ 0's padding) to string [§5.1.1]

    // convert string msg into 512-bit/16-integer blocks arrays of ints [§5.2.1]
    var l = msg.length/4 + 2;  // length (in 32-bit integers) of msg + ‘1’ + appended length
    var N = Math.ceil(l/16);   // number of 16-integer-blocks required to hold 'l' ints
    var M = new Array(N);
    for (var i=0; i<N; i++) {
        M[i] = new Array(16);
        for (var j=0; j<16; j++) {  // encode 4 chars per integer, big-endian encoding
            M[i][j] = (msg.charCodeAt(i*64+j*4)<<24) | (msg.charCodeAt(i*64+j*4+1)<<16) |
                      (msg.charCodeAt(i*64+j*4+2)<<8) | (msg.charCodeAt(i*64+j*4+3));
        }
    }
    // add length (in bits) into final pair of 32-bit integers (big-endian) [5.1.1]
    // note: most significant word would be (len-1)*8 >>> 32, but since JS converts
    // bitwise-op args to 32 bits, we need to simulate this by arithmetic operators
    M[N-1][14] = ((msg.length-1)*8) / Math.pow(2, 32); M[N-1][14] = Math.floor(M[N-1][14])
    M[N-1][15] = ((msg.length-1)*8) & 0xffffffff;

    // set initial hash value [§5.3.1]
    var H0 = 0x67452301;
    var H1 = 0xefcdab89;
    var H2 = 0x98badcfe;
    var H3 = 0x10325476;
    var H4 = 0xc3d2e1f0;

    // HASH COMPUTATION [§6.1.2]

    var W = new Array(80); var a, b, c, d, e;
    for (var i=0; i<N; i++) {

        // 1 - prepare message schedule 'W'
        for (var t=0;  t<16; t++) W[t] = M[i][t];
        for (var t=16; t<80; t++) W[t] = ROTL(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1);

        // 2 - initialise five working variables a, b, c, d, e with previous hash value
        a = H0; b = H1; c = H2; d = H3; e = H4;

        // 3 - main loop
        for (var t=0; t<80; t++) {
            var s = Math.floor(t/20); // seq for blocks of 'f' functions and 'K' constants
            var T = (ROTL(a,5) + f(s,b,c,d) + e + K[s] + W[t]) & 0xffffffff;
            e = d;
            d = c;
            c = ROTL(b, 30);
            b = a;
            a = T;
        }

        // 4 - compute the new intermediate hash value
        H0 = (H0+a) & 0xffffffff;  // note 'addition modulo 2^32'
        H1 = (H1+b) & 0xffffffff;
        H2 = (H2+c) & 0xffffffff;
        H3 = (H3+d) & 0xffffffff;
        H4 = (H4+e) & 0xffffffff;
    }

    return H0.toHexStr() + H1.toHexStr() + H2.toHexStr() + H3.toHexStr() + H4.toHexStr();
}

//
// function 'f' [§4.1.1]
//
function f(s, x, y, z)
{
    switch (s) {
    case 0: return (x & y) ^ (~x & z);           // Ch()
    case 1: return x ^ y ^ z;                    // Parity()
    case 2: return (x & y) ^ (x & z) ^ (y & z);  // Maj()
    case 3: return x ^ y ^ z;                    // Parity()
    }
}

//
// rotate left (circular left shift) value x by n positions [§3.2.5]
//
function ROTL(x, n)
{
    return (x<<n) | (x>>>(32-n));
}

//
// extend Number class with a tailored hex-string method
//   (note toString(16) is implementation-dependant, and
//   in IE returns signed numbers when used on full words)
//
Number.prototype.toHexStr = function()
{
    var s="", v;
    for (var i=7; i>=0; i--) { v = (this>>>(i*4)) & 0xf; s += v.toString(16); }
    return s;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function GetCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

//----------------------------------------
//
//
// Выше секция вспомагательных методов
//
//----------------------------------------
 
/**
 * Работа с рейтингами в виде звездочек
 */
 
 var init_rating = true;
 
/**
 * Обработчик увода мыши с div'а со звездочками
 */
 
 function RatingLightingMouseOut()
 {
 	if ( !init_rating )
 	{
	 	var max_rating_value = document.getElementById('max_rating_value').value;
	 	var min_rating_value = document.getElementById('min_rating_value').value;
	 	
	 	images_str = document.getElementById( 'cur_rating_image' ).value;
	 	images = images_str.split( ';' );
		for ( i = min_rating_value; i <= images.length; i++ )
		{
			star = document.getElementById( 'star_' + i );
			if ( star != null && images[ i - 1 ] != undefined )
			{
				star.src = images[ i - 1 ];
			}
		}
	}
 }
 
/**
 * Обработчик наведения мыши на звездочку
 */
 
 function RatingLightingMouseOver( star_number )
 { 	
 	var max_rating_value = document.getElementById("max_rating_value").value;
 	var min_rating_value = document.getElementById("min_rating_value").value;

	if ( init_rating )
	{	
		images_str = '';
		for( i = min_rating_value; i <= max_rating_value; i++ )
		{
			star = document.getElementById( 'star_' + i );
	 		images_str += star.src;
	 		if ( i < max_rating_value ) images_str += ';';
		}
		document.getElementById( 'cur_rating_image' ).value = images_str;
		
		init_rating = false;
	}
	  
 	for ( i = min_rating_value; i <= star_number; i++ )
 	{
 		star = document.getElementById( 'star_' + i );
 		star.src = '/images/star-lighting.bmp';
 	}
 	
 	images_str = document.getElementById( 'cur_rating_image' ).value;
 	images = images_str.split( ';' );
	for ( i = star_number + 1; i <= images.length; i++ )
	{
		star = document.getElementById( 'star_' + i );
		if ( star != null && images[ i - 1 ] != undefined )
		{
			star.src = images[ i - 1 ];
		}
	}
 }
 
/**
 * Обработчик клика мыши на звездочке
 */
 
 function RatingChange( star_number )
 {
 	var max_rating_value = document.getElementById( 'max_rating_value' ).value;
 	var min_rating_value = document.getElementById( 'min_rating_value' ).value;
 	
 	for ( i = min_rating_value; i <= max_rating_value; i++ )
 	{
 		star = document.getElementById( 'star_' + i );
 		star.src = '/images/star-empty.bmp';
 	}
 	
 	for ( i = min_rating_value; i <= star_number; i++ )
 	{
 		star = document.getElementById( 'star_' + i );
 		star.src = '/images/star.bmp'; 
 	}
 	
	images_str = '';
	for( i = min_rating_value; i <= max_rating_value; i++ )
	{
		star = document.getElementById( 'star_' + i );
 		images_str += star.src;
 		if ( i < max_rating_value ) images_str += ';';
	}
	document.getElementById( 'cur_rating_image' ).value = images_str;
	
	// получаем параметры для ajax запроса
 	rating = star_number;
 	sourceID = document.getElementById('rating_sourceID').value;
 	moduleID = document.getElementById('rating_moduleID').value;
	
	// отправляем ajax запрос
   	siteName = getSiteName( document.location );
    cookie = GetCookie('_tvoybor');
    if (cookie == null) {
        cookie = sha1Hash(randomNumber(100000, 10000000));
    }
   	url = "http://" + siteName + "/ajax/ratings/add/" + sourceID + "/" + moduleID + "/" + cookie + "/" + rating;
   	loadXMLDoc(url);

   	clearTimeout(clearMessageTimeout);
 } 
 
//---------------------------------------------------------------------------------
// Конец работы с модулем рейтингов
//---------------------------------------------------------------------------------

//---------------------------------------------------------------------------------
// Работа с модулем галереи
//---------------------------------------------------------------------------------

 function reportCategoryCreate()
 { 	
 	if ( 'true' != document.getElementById('recievedMessage').innerHTML )
 	{
 		categoryTitle = document.getElementById( 'gallery_category_title' ).value;
 		if ( '' == categoryTitle || null == categoryTitle )
 		{
 			alert( 'Введите название категории' );
 			return false;
 		}
 		// выводим сообщение об ожидании
 		document.getElementById( 'helpMessage' ).innerHTML = 'Подождите ... ';
 		
 		category_data = "title=" + encodeURI( categoryTitle );

		httpRequest = createHttpRequest();
	 
	    if (httpRequest) {
	    	// передаем дополнительный парамет url для чпу
			url = "/ajax/foto/report/category/create";
			category_data += '&redirect=' + encodeURI( url );
			
			siteName = getSiteName( document.location );
   			url = "http://" + siteName + "/post.php"; 
	        httpRequest.open("POST", url, true);
	        httpRequest.onreadystatechange = processCategoryCreate;
			httpRequest.setRequestHeader("Accept-Charset", "windows-1251");
			httpRequest.setRequestHeader("Accept-Language","ru, en");
			httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			httpRequest.setRequestHeader("Content-length", category_data.length); // Длинна отправляемых данных
			httpRequest.setRequestHeader("Connection", "close");
			httpRequest.send(category_data); // Именно здесь отправляются данные
	        requestTimeout = setTimeout("httpRequest.abort();", 5000);
	    } else {
	        alert("Браузер не поддерживает AJAX");
	    }
   	}
   	else
   	{
   		alert( 'Раздел уже был создан' )
   	}
 }

 function galleryCategoryCreate()
 { 	
 	if ( 'true' != document.getElementById('recievedMessage').innerHTML )
 	{
 		categoryTitle = document.getElementById( 'gallery_category_title' ).value;
 		if ( '' == categoryTitle || null == categoryTitle )
 		{
 			alert( 'Введите название категории' );
 			return false;
 		}
 		// выводим сообщение об ожидании
 		document.getElementById( 'helpMessage' ).innerHTML = 'Подождите ... ';
 		
 		category_data = "title=" + encodeURI( categoryTitle );

		httpRequest = createHttpRequest();
	 
	    if (httpRequest) {
	    	// передаем дополнительный парамет url для чпу
			url = "/ajax/foto/gallery/category/create";
			category_data += '&redirect=' + encodeURI( url );
			
			siteName = getSiteName( document.location );
   			url = "http://" + siteName + "/post.php"; 
	        httpRequest.open("POST", url, true);
	        httpRequest.onreadystatechange = processCategoryCreate;
			httpRequest.setRequestHeader("Accept-Charset", "windows-1251");
			httpRequest.setRequestHeader("Accept-Language","ru, en");
			httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			httpRequest.setRequestHeader("Content-length", category_data.length); // Длинна отправляемых данных
			httpRequest.setRequestHeader("Connection", "close");
			httpRequest.send(category_data); // Именно здесь отправляются данные
	        requestTimeout = setTimeout("httpRequest.abort();", 5000);
	    } else {
	        alert("Браузер не поддерживает AJAX");
	    }
   	}
   	else
   	{
   		alert( 'Раздел уже был создан' )
   	}
 }
   	
   	function processCategoryCreate()
   	{
	    if (httpRequest.readyState == 4) 
		{
			clearTimeout(requestTimeout);
	        // only if "OK"
	        if (httpRequest.status == 200) 
			{
				// ответ сервера имеет следующий вид "<boolean ture/false>_<int category_id>_<error_text>"
	            response=httpRequest.responseText;
			   	// parsing response by "_"
			   	firstIndex = response.indexOf("_");
			   	// boolean operation result
			   	b_result = response.slice(0, firstIndex);
			   	// find last "_"
			   	lastIndex = response.lastIndexOf("_");
			   	// int category id
			   	category_id = response.slice(firstIndex + 1, lastIndex);
			   	// copy text response
			   	text = response.slice(lastIndex + 1, response.length);
			   	
			   	if ( 'true' == b_result )
			   	{
			   		// добавляем созданную категорию в список категорий
			   		// получаем список существующих категорий
			   		content = document.getElementById( 'copyCategories' ).value;
			   		contenIndex = content.indexOf("Отсутствует");
			   		content = content.slice(0, contenIndex);
			   		document.getElementById( 'recievedMessage' ).innerHTML = content;
			   		select = document.getElementById( 'categories' );
			   		// добавляем новую категорию в список
			   		b_add_option = false;
			   		for( i = 0; i < select.length; i++ )
			   		{
			   			if ( select.options[ i ].value == 'null' )
			   			{
			   				select.options[ i ] =  new Option( categoryTitle, category_id );
			   				b_add_option = true;
			   			}
			   		}
			   		if ( !b_add_option )
			   		{
			   			select.options[ select.length ] = new Option( categoryTitle, category_id );

			   			selected_value = select.options[ select.selectedIndex ].value;
			   			selected_text = select.options[ select.selectedIndex ].text;
			   			
						select.options[ select.length - 1 ].value = selected_value;
						select.options[ select.length - 1 ].text = selected_text;
						
						select.options[ select.selectedIndex ].value = category_id;
						select.options[ select.selectedIndex ].text = categoryTitle;
			   		}
			   		// отображаем полученное значение
			   		document.getElementById( 'createCategory' ).innerHTML = document.getElementById('recievedMessage').innerHTML;
			   		document.getElementById( 'helpMessage' ).innerHTML = text;
			   		document.getElementById( 'categoryTitle' ).innerHTML = "Раздел галлереи:";
			   		
			   		document.getElementById('recievedMessage').innerHTML = b_result;
			   		
			   		clearMessageTimeout = setTimeout("document.getElementById('helpMessage').style.display='none';", 1000);
			   	}
			   	else
			   	{
			   		document.getElementById('recievedMessage').innerHTML = b_result;
		 			document.getElementById( 'helpMessage' ).innerHTML = text;
			   	}
	        } else {
	            alert("Не удалось получить данные:\n" + httpRequest.statusText);
	        }
	    }  
   	}
   	
   	var photo_title = '';
   	function PhotoUpdate( url )
   	{
   		photo_title = prompt( 'Введите название фото. Название может состоять из нескольких слов. Ввод через пробел.', '' );
   		if ( photo_title != null && photo_title != '' )
   		{
	 		photo_data = "title=" + encodeURI( photo_title );
	
			httpRequest = createHttpRequest();
		 
		    if (httpRequest) {
		    	// передаем дополнительный парамет url для чпу
				photo_data += '&redirect=' + encodeURI( url );
				siteName = getSiteName( document.location );
				url = "http://" + siteName + "/post.php"; 
		        httpRequest.open("POST", url, true);
		        httpRequest.onreadystatechange = processPhotoUpdate;
				httpRequest.setRequestHeader("Accept-Charset", "windows-1251");
				httpRequest.setRequestHeader("Accept-Language","ru, en");
				httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				httpRequest.setRequestHeader("Content-length", photo_data.length); // Длинна отправляемых данных
				httpRequest.setRequestHeader("Connection", "close");
				httpRequest.send(photo_data); // Именно здесь отправляются данные
		        requestTimeout = setTimeout("httpRequest.abort();", 5000);
		    } else {
		        alert("Браузер не поддерживает AJAX");
		    }
   		}
   		else if ( photo_title == '' )
   		{
   			alert( 'Вы не ввели название фото' );
   		}
   	}
   	
   	var update_url = '';
   	var delete_url = '';
   	function processPhotoUpdate()
   	{
	    if (httpRequest.readyState == 4) 
		{
			clearTimeout(requestTimeout);
	        // only if "OK"
	        if (httpRequest.status == 200) 
			{
				// ответ сервера имеет следующий вид "<boolean ture/false>_<int photo_id>_<text error>"
	            response=httpRequest.responseText;
			   	// parsing response by "_"
			   	firstIndex = response.indexOf("_");
			   	// boolean operation result
			   	b_result = response.slice(0, firstIndex);
			   	// find last "_"
			   	lastIndex = response.lastIndexOf("_");
			   	// int photo alias
			   	photo_alias = response.slice(firstIndex + 1, lastIndex);
			   	// copy text response
			   	text = response.slice(lastIndex + 1, response.length);
			   	if ( 'true' == b_result )
			   	{
			   		alert( text );
			   		document.getElementById( 'photo_title' ).innerHTML = photo_title;
			   		document.getElementById( 'pageTitle' ).innerHTML = photo_title;
			   		
			   		update_path = '';
			   		update_path += document.getElementById( 'photoUpdate' ).onclick;
			   		firstIndex = update_path.indexOf("/");
			   		lastIndex = update_path.lastIndexOf("/");
			   		new_update_path = update_path.slice(firstIndex, lastIndex + 1);
			   		if ( '' != new_update_path ) update_url = new_update_path;
			   		new_update_path = update_url + photo_alias;
			   		document.getElementById( 'photoUpdate' ).onclick = function onclick(event) {PhotoUpdate(new_update_path); }
			   		
			   		delete_path = '';
			   		delete_path += document.getElementById( 'photoDelete' ).onclick;
			   		firstIndex = delete_path.indexOf("/");
			   		lastIndex = delete_path.lastIndexOf("/");
			   		new_delete_path = delete_path.slice(firstIndex, lastIndex + 1);
			   		if ( '' != new_delete_path ) delete_url = new_delete_path;
			   		new_delete_path = delete_url + photo_alias;
			   		document.getElementById( 'photoDelete' ).onclick = function onclick(event) {PhotoConfirmDeleting(new_delete_path); }
			   	}
			   	else
			   	{
			   		alert( text );
			   	}
	            
	        } else {
	            alert("Не удалось получить данные:\n" + httpRequest.statusText);
	        }
	    }
   	}
   	
//---------------------------------------------------------------------------------
// Конец работы с модулем галереи
//---------------------------------------------------------------------------------

//----------------------------------------------------------
//--------------------------END AJAX------------------------
//----------------------------------------------------------



//subcategories for catalogue

var nameOfSelect = null



function FullSubselect( selectName )
{
	nameOfSelect = selectName
	categoryID = document.getElementById( selectName ).value
	url = '/ajax/catalogue/ajax/fullsubselect/' + categoryID
   	httpRequest = createHttpRequest()
 
    if ( httpRequest )
	{
        httpRequest.onreadystatechange = ProcessSubcategories
        httpRequest.open( "GET", url, true )
        httpRequest.send( null )
    }
	else
        alert( "Браузер не поддерживает AJAX" )
}



function ProcessSubcategories()
{
	if ( httpRequest.readyState == 4 )
        if ( httpRequest.status == 200 )
		{
			string = ''
			categoryID = null
			categoryName = null
			startIndex = 0
			lastIndex = 0
            response = httpRequest.responseText
			ua = navigator.userAgent.toLowerCase()
			isIE = ( ua.indexOf( 'msie' ) != -1 && ua.indexOf( 'opera' ) == -1 && ua.indexOf( 'webtv' ) == -1 )
			
			while ( response.indexOf( '/', lastIndex ) != -1 )
            {
            	startIndex = lastIndex
            	lastIndex = response.indexOf( '/', lastIndex )
            	categoryID = response.slice( startIndex, lastIndex )
            	lastIndex++
            	
            	startIndex = lastIndex
            	lastIndex = response.indexOf( '*', lastIndex )
            	categoryName = response.slice( startIndex, lastIndex )
            	lastIndex++
            	
            	string += '<option value="' + categoryID + '">' + categoryName + '</option>'
            }
            
            if ( isIE )
            	document.getElementById('sub' + nameOfSelect).outerHTML = '<select name="sub' + nameOfSelect + '">' + string + '</select>'
            else
            	document.getElementById('sub' + nameOfSelect).innerHTML = string
        }
		else
            alert( "Не удалось получить данные:\n" + httpRequest.statusText )
}

//end of subcategories for catalogue



//checking alias

function CheckAlias( id )
{
	if ( document.getElementById('alias_' + id).value == '' )
	{
		alert( 'Вы должны ввести уникальный алиас для этой организации!' )
		return
	}
	
	url = '/ajax/newtasks/ajax/checkalias/' + document.getElementById('alias_' + id).value + '/' + id
   	httpRequest = createHttpRequest()
 
    if ( httpRequest )
	{
        httpRequest.onreadystatechange = ProcessCheckAlias
        httpRequest.open( "GET", url, true )
        httpRequest.send( null )
    }
	else
        alert( "Браузер не поддерживает AJAX" )
}



function ProcessCheckAlias()
{
	if ( httpRequest.readyState == 4 )
        if ( httpRequest.status == 200 )
		{
			response = httpRequest.responseText
			answer = response.slice( 0, response.indexOf( '/' ) )
			id = response.slice( response.indexOf( '/' ) + 1 )
			
			if ( answer == 'error' )
				alert( 'Произошла ошибка при работе с базой данных! Пожалуйста, повторите попытку или введите новое значение алиаса.' )
				
			if ( answer == 'ok' )
			{
				document.getElementById('addButton_' + id).disabled = false
				alert( 'Теперь вы можете добавить эту организацию в каталог' )
			}
			
			if ( answer == 'bad' )
				alert( 'Этот алиас уже используется другой организацией! Попробуйте ввести другое значение.' ) 	
		}
		else
            alert( "Не удалось получить данные:\n" + httpRequest.statusText )
}

//end of chicking alias



//checking alias in editting firm

function CatalogueChangeAlias()
{
	document.getElementById('submit').disabled = true
	
	if ( document.getElementById('alias').value == '' )
	{
		alert( 'Вы должны ввести уникальный алиас для этой организации!' )
		return
	}
	
	url = '/ajax/newtasks/ajax/checkalias/' + document.getElementById('alias').value + '/' + 0;
   	httpRequest = createHttpRequest()
   	
    if ( httpRequest )
	{
        httpRequest.onreadystatechange = ProcessCatalogueChangeAlias
        httpRequest.open( "GET", url, true )
        httpRequest.send( null )
    }
	else
        alert( "Браузер не поддерживает AJAX" )
}



function ProcessCatalogueChangeAlias()
{
	if ( httpRequest.readyState == 4 )
        if ( httpRequest.status == 200 )
		{
			response = httpRequest.responseText
			answer = response.slice( 0, response.indexOf( '/' ) )
			
			if ( answer == 'error' )
				alert( 'Произошла ошибка при работе с базой данных! Пожалуйста, повторите попытку или введите новое значение алиаса.' )
				
			if ( answer == 'ok' )
				document.getElementById('submit').disabled = false
			
			if ( answer == 'bad' )
				alert( 'Этот алиас уже используется другой организацией! Попробуйте ввести другое значение.' ) 	
		}
		else
            alert( "Не удалось получить данные:\n" + httpRequest.statusText )
}

//end of checking alias in editting firm



//checking ratings in category

function CatalogueChangeRating( categoryID, firmID )
{
	document.getElementById('submit').disabled = true
	
	url = '/ajax/catalogue/ajax/checkrating/' + categoryID + '/' + document.getElementById('rating_' + categoryID).value + '/' + firmID
   	httpRequest = createHttpRequest()
   	
    if ( httpRequest )
	{
        httpRequest.onreadystatechange = ProcessCatalogueChangeRating
        httpRequest.open( "GET", url, true )
        httpRequest.send( null )
    }
	else
        alert( "Браузер не поддерживает AJAX" )
}



function ProcessCatalogueChangeRating()
{
	if ( httpRequest.readyState == 4 )
        if ( httpRequest.status == 200 )
		{
			response = httpRequest.responseText
			
			if ( response == 'error' )
			{
				alert( 'Произошла ошибка при работе с базой данных! Пожалуйста, измените рейтинг для этой категории.' )
				return
			}
			
			if ( response == 'ok' )
			{
				document.getElementById('submit').disabled = false
				return
			}
			
			alert( 'Этот рейтинг имеет фирма "' + response + '". Пожалуйста, измените рейтинг.' )
		}
		else
            alert( "Не удалось получить данные:\n" + httpRequest.statusText )
}

//end of checking ratings in category