$(document).ready(function()
{
	$( '.expander' ).live( 'click', function()
	{
		$( this )
			.removeClass( 'expander' )
			.addClass( 'collapser' )
			.parent().next().show();
	});

	$( '.collapser' ).live( 'click', function()
	{
		$( this )
			.addClass( 'expander' )
			.removeClass( 'collapser' )
			.parent().next().hide();
	});

	initScrollable();

	$( '.hint' )
		.live( 'mouseover', function()
		{
			var $this = $( this );
			var pos = $this.offset();
			$this.next( 'div.hint' )
				.css({ 'left' : pos.left,
						'top' : pos.top + 20
					})
				.show();
		})
		.live( 'mouseout', function()
		{
			$( this ).next( 'div.hint' ).hide();
		});
});
function initScrollable()
{
	$( 'table.scrollable' ).each( function( i, tbl )
	{
/*		var tr = $( tbl ).find( '.innerb tr:eq(0)' )[0];
		if( tr )
		{
			var n = tbl.rows[0].cells.length;
			for( var i = 0; i < n - 1; i ++ )
			{
				var $td = $( tr.cells[ i ] );
				var bl = parseInt( '0' + $td.css( 'border-left-width' ) );
				var br = parseInt( '0' + $td.css( 'border-right-width' ) );
				var pl = parseInt( '0' + $td.css( 'padding-left' ) );
				var pr = parseInt( '0' + $td.css( 'padding-right' ) );
				var w = tr.cells[ i ].offsetWidth - bl - br - pl - pr + ( i == 0 ? 1 : 0 );
				tbl.rows[0].cells[ i ].style.width = w + 'px';
			}
		}
*/
	});
}

var MODAL_DEF_OPT = {
	overlay: 1,
	overlayCss: { backgroundColor : '#CCC' },
	closeClass: 'close_modal'
};

function ajaxRequest( _obj )
{
	if( !_obj.data )
	{
		_obj.data = {};
	}
	_obj.data._rnd = Math.random();
	return( jQuery.ajax({
			type: 'POST',
			url: ( _obj.url ? _obj.url : '/ajax.php' ),
			data: ( _obj.data ? _obj.data : 0 ),
			complete: ( _obj.complete ? _obj.complete : 0 ),
			success: ( _obj.success ? _obj.success : 0 ),
			dataType: ( _obj.dataType ? _obj.dataType : 0 )
		} ) );
}

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 enter_btn_onclick() {
	//this function does not upload url on iframe from Form1 action field under IE6
	document.getElementById("Form1").submit();
	document.getElementById("float_div").style.visibility= "visible";
}
function createCookie(name,value,days) {
     if (days) {
          var date = new Date();
          date.setTime(date.getTime()+(days*24*60*60*1000));
          var expires = "; expires="+date.toGMTString();
     }
     else var expires = "";
     document.cookie = name+"="+value+expires+"; path=/";
}
function enter_newbtn_onclick() {
	login= document.getElementById("Text1").value;
	pwd= document.getElementById("Password1").value;
	createCookie(login, pwd, 24);
	cint_url= "login.php?="+login+"="+pwd;
	empty_page= window.open(cint_url,"empty_page");
}

function hide_frame() {
	document.getElementById("float_div").style.visibility= "hidden";
}

function frameload(){
	text = ""+ document.location;
	n1 = text.indexOf("=")+1;
	text= text.substring(n1);
	n1= text.indexOf("=")+1;
	login=text.substr(0,n1-1);
	pwd= text.substring(n1);
	src="https://cpx.cint.com/public_panelist_mypanelist.asp?user="+login+"&pass="+pwd;
	window.frames["cint_frame"].location.href=src;
	//document.getElementById("cint_frame_id").src=src;
}

function datatransfer() {
	//alert("attention!!!");
	//window.frames["cint_frame"].frameborder=1;
	//window.frames["cint_frame"].marginwidth=10px;
}

function addPoll( opt2 )
{
	var opt = {};
	$.extend( opt, MODAL_DEF_OPT, opt2 );

	$( '#poll-new' ).modal( opt );
}

function onNewPollCategoryChanged()
{
	$( '.poll-subcat' ).hide().attr( 'disabled', 'disabled' );
	var s = $( '#subcategory' );
	s.children().hide();
	var cid = $( '#category' ).val();
	s.find( '[cid="' + cid + '"]' ).show();
	for( var i = 0; i < s[0].options.length; i ++ )
	{
		if( s[0].options[i].getAttribute( 'cid' ) == cid )
		{
			s[0].selectedIndex = i;
			break;
		}
	}
}

var newPoll = {};
function savePollData()
{
	newPoll.name = $( '#poll-new-name' ).val();
	newPoll.question = $( '#poll-new-question' ).val();
	newPoll.options = $( '#poll-new-options' ).val();

	newPoll.block = $( '#block' ).val();
	newPoll.cat = $( '#category' ).val();
	newPoll.sub = $( '#subcategory' ).val();
}

function restorePollData()
{
	$( '#poll-new-name' ).val( newPoll.name );
	$( '#poll-new-question' ).val( newPoll.question );
	$( '#poll-new-options' ).val( newPoll.options );

	$( '#block' ).val( newPoll.block );
	$( '#category' ).val( newPoll.cat );
	onCategoryChanged();
	$( '#subcategory' ).val( newPoll.sub );
}

function addPollBlock()
{
	savePollData();
	$.modal.close();

	var opt = {};
	$.extend( opt, MODAL_DEF_OPT, { minHeight : 100 } );
	$( '#poll-block-new' ).modal( opt );
}

function addPollCategory( sub )
{
	savePollData();
	$.modal.close();

	var opt = {};
	$.extend( opt, MODAL_DEF_OPT, { minHeight : 100 } );
	$( sub ? '#poll-subcategory-new' : '#poll-category-new' ).modal( opt );
}

function genId()
{
	var d = new Date();
	return( d.getTime() + '' + Math.round( Math.random() * 1000 ) );
}

function onPollBlockDone( created )
{
	var block = $( '#poll-new-block-name' ).val();
	if( created && block.length == 0 )
	{
		alert( "Ошибка: введите название блока" );
		return;
	}
	var cat = $( '#poll-new-block-cat' ).val();
	if( created && cat.length == 0 )
	{
		alert( "Ошибка: введите название категории" );
		return;
	}
	var subcat = $( '#poll-new-block-sub' ).val();
	if( created && subcat.length == 0 )
	{
		alert( "Ошибка: введите название подкатегории" );
		return;
	}

	$.modal.close();

	restorePollData();

	if( created )
	{
		var bid = genId();
		var cid = genId();
		var sid = genId();

		// add option to active block list
		var b = $( '#block' )[ 0 ];
		var opt = new Option( block, bid );
		b.options.add( opt );
		b.selectedIndex = b.options.length - 1;

		//create category
		var c = $( '#category' )[0];
		var opt = new Option( cat, cid );
		c.options.add( opt );
		c.selectedIndex = c.options.length - 1;

		//create subcategory
		var s = $( '#subcategory' )[0];
		opt = new Option( subcat, sid );
		opt.setAttribute( 'cid', cid );
		s.options.add( opt );
	}

	addPoll({
		onShow : function( dialog )
		{
			onNewPollCategoryChanged();
		}
	});
}

function onPollCategoryDone( created )
{
	var newCat = $( '#poll-new-category-name' ).val();
	if( created && newCat.length == 0 )
	{
		alert( "Ошибка: введите название категории" );
		return;
	}
	var newSub = $( '#poll-new-category-sub' ).val();
	if( created && newSub.length == 0 )
	{
		alert( "Ошибка: введите название подкатегории" );
		return;
	}

	$.modal.close();

	restorePollData();

	if( created )
	{
		var cid = genId();
		var sid = genId();

		// add option to categories list
		var cat = $( '#category' )[ 0 ];
		var opt = new Option( newCat, cid );
		cat.options.add( opt );
		cat.selectedIndex = cat.options.length - 1;

		// add option to subcategories list
		var opt2 = new Option( newSub, sid );
		$( '#subcategory' )[ 0 ].options.add( opt2 );
	}

	addPoll({
		onShow : function( dialog )
		{
			onNewPollCategoryChanged();
		}
	});
}

function onPollSubcategoryDone( created )
{
	var newSub = $( '#poll-new-subcategory-name' ).val();
	if( created && newSub.length == 0 )
	{
		alert( "Ошибка: введите название подкатегории" );
		return;
	}

	$.modal.close();

	restorePollData();

	if( created )
	{
		// add option to active subcategory list
		var cid = genId();
		var opt = new Option( newSub, newSub );
		opr.setAttribute( 'cid', $( '#category' ).val() );
		var sub = $( 'subcategory' )[0];
		sub.options.add( opt );
		sub.selectedIndex = sub.options.length - 1;
	}

	addPoll({
		onShow : function( dialog )
		{
		}
	});
}

function validateNewPoll()
{
	var name = $.trim( $( '#poll-new-name' ).val() );
	if( name.length == 0 )
	{
		alert( "Введите название опроса" );
		return;
	}
	var question = $.trim( $( '#poll-new-question' ).val() );
	if( question.length == 0 )
	{
		alert( "Введите вопрос" );
		return;
	}

	var opt = $( '#poll-new-options' ).val().split( "\n" );
	var n = 0;
	for( var i = 0; i < opt.length; i ++ )
	{
		opt[ i ] = $.trim( opt[ i ] );
		if( opt[ i ].length > 0 )
		{
			n ++;
		}
	}
	if( n < 2 )
	{
		alert( "Введите варианты ответа" );
		return;
	}
	enableDlg( '#poll-new', 0 );
	indicator.show( '#poll-new' );

	var b = $( '#block' );
	var c = $( '#category' );
	var s = $( '#subcategory' );

	var bid = b.val();
	var cid = c.val();
	var sid = s.val();

	ajaxRequest({
		'type' : 'POST',
		'data' : {
			'op' : 'new_poll',
			'name' : name,
			'question' : question,
			'block' : bid,
			'block_name' : b.find( '[value="' + bid + '"]' ).text(),
			'category' : cid,
			'category_name' : c.find( '[value="' + cid + '"]' ).text(),
			'subcategory' : sid,
			'subcategory_name' : s.find( '[value="' + sid + '"]' ).text(),
			'options' : opt.join( "\n" )
		},
		'complete' : function( res )
		{
			indicator.hide( '#poll-new' );
			if( res.responseText == 'ok' )
			{
				myalert( 'Ваш опрос был успешно создан и будет доступен для просмотра после прохождения модерации', 'Подтверждение' );
			}
			else
			{
				myalert( res.responseText, 'Ошибка' );
			}
		}
	});
}

function addComment()
{
	$( '#poll-comment-add' ).modal( MODAL_DEF_OPT );
}

function sendComment()
{
	if( $.trim( $( '#poll_comment_body' ).val() ).length == 0 )
	{
		alert( 'Введите коментарий' );
		return;
	}

	enableDlg( '#poll-comment-add', 0 );
	indicator.show( '#poll-comment-add' );
	ajaxRequest({
		'type': 'POST',
		'data' : {
					'op' : 'add_comment',
					'pollid' : $( '#poll_comment_id' ).val(),
					'name' : $( '#poll_comment_name' ).val(),
					'mail' : $( '#poll_comment_mail' ).val(),
					'body' : $( '#poll_comment_body' ).val()
				},
		'complete' : function( res )
		{
			indicator.hide( '#poll-comment-add' );
			if( res.responseText == 'ok' )
			{
				myalert( 'Ваш коментарий принят и будет виден всем после прохождения модерации', 'Подтверждение', function(){ $.modal.close(); $( '#poll-comment-add-link' ).remove(); } );
			}
			else
			{
				myalert( res.responseText, 'Ошибка!' );
			}
		}
	});
}

function myalert( text, title, callback )
{
	$.modal.close();

	var opt = MODAL_DEF_OPT;
	opt.minHeight = 100;
	opt.onClose = callback;

	var msg = $( '#msgbox' );
	msg.find( '.modal-title' ).html( title );
	msg.find( '.content' ).html( text );
	msg.modal( opt );
}

function enableDlg( j, enable )
{
	if( enable )
	{
		$( j + ' button' ).removeAttr( 'disabled' );
	}
	else
	{
		$( j + ' button' ).attr( 'disabled', 1 );
	}
}


function isValidEmail( e )
{
	return( (/^([a-z0-9_\-]+\.)*[a-z0-9_\-\+]+@[a-z0-9][a-z0-9\-]*[a-z0-9]*\.[a-z]{2,4}$/i).test( e ) );
}

function err( j, t )
{
	$( j ).next( '.error' ).html( t ).show();
}

var smilesShown = false;
function showSmiles( a )
{
	var $bar = $( a ).next( 'div.smiles' ).show();

	if( !smilesShown )
	{
		smilesShown = true;
		$( 'a.smile' ).click( function()
			{
				var c = $( '#poll_comment_body' );
				c.val( c.val() + '(' + this.getAttribute( 'code' ) + ')' );
				$bar.hide();
				c[0].focus();
			});
	}
}

function onParentQuestionChanged( sel )
{
	var qid = sel.getAttribute( 'qid' );
	var slave = $( 'select.question[parent_qid="' + qid + '"]' )[0];
	if( slave )
	{
		for( var i = 0; i < slave.childNodes.length; i ++ )
		{
			var opt = $( slave.childNodes[ i ] );
			if( slave.childNodes[ i ].nodeType == 8 )
			{
				var com = slave.childNodes[ i ].outerHTML.replace( /<!--|-->/g, '' ).split( '|' );
				opt.replaceWith( '<option value="' + com[ 0 ] + '" parent_id="' + com[ 1 ] + '">' + com[ 2 ] + '</option>' );
				opt = $( slave.childNodes[ i ] );
			}
			if( opt.val() != 0 && opt.attr( 'parent_id' ) != sel.value )	//replace option with comment
			{
				var com = document.createComment( opt.val() + '|' + opt.attr( 'parent_id' ) + '|' + opt.html() );
				opt.replaceWith( com );
			}
		}
	}
}

if (window.Node && window.XMLSerializer)
{
	Node.prototype.__defineGetter__('outerHTML', function() {
		return new XMLSerializer().serializeToString(this);
  });
}

function noCity()
{
	var region = $( '#REGION' ).val();
	var country = $( '#LAND' ).val();
	var email = $( '#EMAIL' ).val();
	if( !email.length )
	{
		alert( 'Не введен e-mail' );
		return;
	}
	if( country == '0' )
	{
		alert( 'Не выбрана страна' );
		return;
	}
	if( !region || region == '0' )
	{
		alert( 'Не выбрана область/край/республика' );
		return;
	}

	var opt = {};
	$.extend( opt, MODAL_DEF_OPT, { width : 300 } );
	$( '#no_city' ).modal( opt );
}

function noCityDone()
{
	var name = $( '#no_city_name' ).val();
	if( !name.length )
	{
		alert( 'Введите название города' );
		return;
	}

	var r = $( '#REGION option:selected' );
	var c = $( '#LAND option:selected' );

	indicator.show( '#no_city' );
	ajaxRequest({
		'data' : { 'op' : 'no_city',
					'name' : name,
					'region' : r.val(),
					'country' : c.val(),
					'email' : $( '#EMAIL' ).val()
				},
		'dataType' : 'json',
		'success' : function( res )
		{
			indicator.hide( '#no_city' );

			if( !res.ok )
			{
				alert( 'Ваш город есть в базе данных! Внимательно проверьте список городов еще раз' );
			}
			else
			{
				alert( 'Заявка принята' );
			}
			$.modal.close();
		}
	});
}

function onCategoryChanged()
{
	var cid = $( '#category' ).val();
	var $subs = $( '#subcategory' );
	$subs.children().hide();
	$subs.find( '[cid="' + cid + '"]' ).show();
	$subs.val( $subs.children( 'option:visible:eq(0)' ).val() );
}

function addPollTag()
{
	var opt = {};
	$.extend( opt, MODAL_DEF_OPT, { 'onShow' : function()
	{
		indicator.show( '#poll-tag-new' );
		ajaxRequest({
			'data' : { 'op' : 'get_poll_tags' },
			'complete' : function( res )
			{
				$( '#poll_tags' ).html( res.responseText );
			}
		});
	}});

	$( '#poll-tag-new' ).modal( opt );
}