function ExpandLongString ( obj )
{
    var parent = obj.parentNode;
        parent = parent.parentNode;
    
    $( parent ).children ( 'span:eq(0)' ).hide();
    $( parent ).children ( 'span:eq(1)' ).show();
    $( parent ).children ( 'span:eq(2)' ).show();
}
function CollapseLongString ( obj )
{
    var parent = obj.parentNode;
        parent = parent.parentNode;
    
    $( parent ).children ( 'span:eq(1)' ).hide();
    $( parent ).children ( 'span:eq(2)' ).hide();
    $( parent ).children ( 'span:eq(0)' ).show();
}
function GetYScroll ()
{
	var yScroll = 0;
	if ( window.innerHeight && window.scrollMaxY )
	{
		yScroll = window.innerHeight + window.scrollMaxY;
		var deff = document.documentElement;
		var hff = ( deff && deff.clientHeight ) || document.body.clientHeight || window.innerHeight || self.innerHeight;
		yScroll -= ( window.innerHeight - hff );
	} else if ( document.body.scrollHeight > document.body.offsetHeight ) {
		yScroll = document.body.scrollHeight;
	} else {
		yScroll = document.body.offsetHeight;
	}
	return yScroll;
}
function GetXScroll ()
{
	var xScroll = 0;
	if ( window.innerWidth && window.scrollMaxX )
	{
		xScroll = window.innerWidth + window.scrollMaxX;
		var deff = document.documentElement;
		var wff = ( deff && deff.clientWidth ) || document.body.clientWidth || window.innerWidth || self.innerWidth;
		xScroll -= ( window.innerWidth - wff );
	} else if ( document.body.scrollWidth > document.body.offsetWidth ) {
		xScroll = document.body.scrollWidth;
	} else {
		xScroll = document.body.offsetWidth;
	}
	return xScroll;
}
function GetScrollTop ()
{
    var ht1 = document.documentElement.scrollTop;
	var ht2 = document.body.scrollTop;
	
	if ( ( ht1 == 0 && ht2 > 0 ) || ht1 == ht2 )
	{
		var h = ht2;
	} else if ( ht1 > 0 ) {
		var h = ht1;
	}
	
	return h;
}
function GenPopupPos ( width, height )
{
    var h1 = document.body.offsetHeight;
	var h2 = GetScrollTop();
	var top = h1 / 2 - height + h2;
	var left = ( GetXScroll () / 2 - width );
	
	var result = {
	    top  : top,
	    left : left
	};
	
	return result;
}
// photos
function ShowPhotoDialog ( id, report )
{
    $( '#photo_bg' ).remove();
    //$( '#photo_dialog_container' ).remove();
    $( 'body' ).append ( '<div id="photo_bg"></div>' );
	
    $( '#photo_bg' ).css ( { height: GetYScroll() + 'px', opacity: 0.8 } );
    //$( 'body' ).append ( '<div id="photo_dialog_container"><div id="psh_close"><a href="javascript:void(0);" onclick="HidePhoto();">Закрыть окно</a></div><div id="psh_content"></div></div>' );
    ShowPPhoto ( id, report );
}
function HidePhoto ()
{
    $( '#photo_bg' ).remove();
    $( '#big_photo, #arr_left, #arr_right' ).remove();
    //$( '#photo_dialog_container' ).remove();
}
function ShowPPhoto ( id, report )
{
    $( '#big_photo, #arr_left, #arr_right' ).remove();
    var next = $( '#thumbnail_' + id ).next();
    var prev = $( '#thumbnail_' + id ).prev();
    
    if ( next.length == 0 )
    {
        next = $( '#photos_table_' + report + ' > div:first' );
    }
    
    if ( prev.length == 0 )
    {
        prev = $( '#photos_table_' + report + ' > div:last' );
    }
        
    var next_id = next.attr ( 'id' );
        next_id = next_id.replace ( 'thumbnail_', '' );
        
    var prev_id = prev.attr ( 'id' );
        prev_id = prev_id.replace ( 'thumbnail_', '' );
    var pos = GenPopupPos ( 74, 15 );
    $( 'body' ).append ( '<div id="popup_ph_indicator" style="top: ' + ( pos.top - 250 ) + 'px; left: ' + pos.left + 'px;">Идет загрузка...</div><div id="big_photo"><a id="psh_close" href="javascript:void(0);" onclick="HidePhoto();">Закрыть</a></div><img src="/images/spacer.gif" width="36" height="169" id="arr_right" /><img src="/images/spacer.gif" width="36" height="169" id="arr_left" />' );
    var img = new Image();
    
    img.onload = function () {
        var h = $( '#big_photo' ).height();
        var w = $( '#big_photo' ).width();
        
        var pos = GenPopupPos ( w / 2, h / 2 );
        
        $( '#popup_ph_indicator' ).remove();
        $( '#big_photo' )
            .css ( { top: pos.top + 'px', left: pos.left + 'px' } )
            .animate ( { opacity: 'show' }, 200, 'linear', function () {
                $( '#arr_left' )
                    .css ( { top: ( pos.top + parseInt ( h / 2 ) - 85 ) + 'px',
                             left: ( pos.left - 42 ) + 'px' } )
                    .bind ( 'click', function () {
                        ShowPPhoto ( prev_id, report );
                    } )
                    .animate ( { opacity: 'show' }, 200 );
                    
                $( '#arr_right' )
                    .css ( { top: ( pos.top + parseInt ( h / 2 ) - 85 ) + 'px',
                             left: ( pos.left + w + 6 ) + 'px' } )
                    .bind ( 'click', function () {
                        ShowPPhoto ( next_id, report );
                    } )
                    .animate ( { opacity: 'show' }, 200);
            } );
    }
    
    $( '#big_photo' ).append ( img );
    img.src = '/pic/photos/' + report + '/' + id + '.jpg';
}

function SendOp ()
{	
    client_request ( 'pubs', 'save_opinion', '', 'POST', '', 'AfterSendOp', false, 'op_form' );
}
function AfterSendOp ( data )
{
    $( '#errors' ).html ( '' );
    
    if ( data.errors )
    {
        $( '#errors' ).html ( data.errors );
    } else {
        $( '#errors' ).html ( '<div class="msg">Ваш отзыв отправлен на проверку.</div>' );
        
        setTimeout ( function () {
            $( '#errors' ).html ( '' );
            $( '#op_form' ).find ( 'input:text' ).val ( '' );
            $( '#op_form' ).find ( 'textarea' ).val ( '' );
        }, 3000 );
    }
}
function SendOrder ()
{
    client_request ( 'order', 'send_order', '', 'POST', '', 'AfterSendOrder', false, 'order_form' );
}
function AfterSendOrder ( data )
{
    $( '#errors' ).html ( '' );
    
    if ( data.errors )
    {
        $( '#errors' ).html ( data.errors );
    } else {
        $( '#errors' ).html ( '<div class="msg">Ваш ваш заказ отправлен нашим менеджерам. С Вами свяжутся в ближайшее время.</div>' );
        
        setTimeout ( function () {
            $( '#errors' ).html ( '' );
            $( '#order_form' ).find ( 'input:text' ).val ( '' );
            $( '#order_form' ).find ( 'textarea' ).val ( '' );
        }, 3000 );
    }
}
function GetMap ( lat, lng )
{
    if ( GBrowserIsCompatible () )
	{
		map = new GMap2 ( document.getElementById( 'google_map' ) );
		map.addControl ( new GSmallMapControl () );
		map.addControl ( new GMapTypeControl () );
				
		center = new GLatLng ( lat, lng );
		map.setCenter ( center, 16 );
		
		var marker = new GMarker ( center );
		map.addOverlay ( marker );
	}
}

//***** ОТПРАВКА ЗАЯВОК НА ПРОВЕДЕНИЕ МЕРОПРИЯТИЯ *****//

function SendClientOrder() {	
	
	$("#sendStatus").hide();
	
	$("input[name='fio']").addClass('.invalidField');
	
	/**
	 * Объект, содержащий данные формы, признаки обязательных полей и регулярные выражения для их валидации  
	 */	
	var data = {
		place:new fieldItem('input', 'name', 'place', true, /^[а-яА-Яa-zA-Z0-9-_]+$/), 
		fio:new fieldItem('input', 'name', 'fio', true, /[а-яА-Яa-zA-Z\s]+/),
		org:new fieldItem('input', 'name', 'org', false),
		phone:new fieldItem('input', 'name', 'phone', true, /^\(\d+\)(\d|-|\s)+\d$/),
		mail:new fieldItem('input', 'name', 'mail', true, /^[a-zA-Z][a-zA-Z0-9-_]*(\.[a-zA-Z0-9-_]+)*@[a-zA-Z]([a-zA-Z0-9-_]*)(\.[a-zA-Z]{2,4})$/),
		date:new fieldItem('input', 'name', 'date', true, /^[0-3][0-9]-[0|1][0-9]-\d\d\d\d$/),
		count:new fieldItem('input', 'name', 'count', true, /^\d+$/),
		format:new fieldItem('select', 'name', 'format', true, /^[0-9]+(,[0-9]+)*$/),		
		specials:new fieldItem('select', 'name', 'specials', false),
		notes:new fieldItem('input', 'name', 'notes', false)
	};	
	
	var data_toSend = {};
	
	// валидация пользовательских данных
	var itsOK = true;
	
	for (field in data) {		
		var f = data[field];		
		f.checkIt();		
		data_toSend[field] = f.valid ? f.value : "";
		itsOK = !f.valid ? false : itsOK;
	}
	
	if (itsOK) {
		$.post("/.system/tools/orders/send_order.php", data_toSend, onSaveClientOrder);
	} else {
		alert("Проверьте правильность заполнения полей!");
	}
}

/**
 * Объект-оболочка для элементов формы. Самовалидируется и выделяет неправильные поля
 * @param {String} type Тип элемента управления (input, select...)
 * @param {String} attrName Имя атрибута, по которому находится элемент
 * @param {String} attrVal Значение этого атрибута
 * @param {Boolean} required Признак обязательного к заполнению поля
 * @param {RegExp} checkExp Регулярное выражение для валидации значения поля
 */
function fieldItem(type, attrName, attrVal, required, checkExp){
		
	this.domEl = $(type + "[" + attrName + "='" + attrVal +  "']");
	
	this.value = (type == "input") ? $(this.domEl).attr("value") : $(this.domEl).val();
	this.value = "" + (this.value || "");	
	this.value.replace(/^\s+/, "");
	this.value.replace(/\s+$/, "");	
	
	this.required = required;
	this.valid = true;
	this.checkExp = checkExp;	
}

fieldItem.prototype = {
	
	checkIt:function(){
		if (this.required && this.checkExp) {
			this.valid = this.checkExp.test(this.value);			
		}
		if (!this.valid) {
			$(this.domEl).addClass('invalidField');			
		} else {
			$(this.domEl).removeClass('invalidField');
		}
	}	
}

function onSaveClientOrder(responseText) {	
	$("input:not(:hidden)[class!='op_button']").val("");
	$("select[name='format']").val([]);
	$("select[name='specials']").val([]);	
	$("#sendStatus").text("Заявка отправлена").show();
	
	setTimeout(function() {$("#sendStatus").hide();} , 3000);
}