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

function ajaxRequest( _obj )
{
	return( jQuery.ajax({
			type: ( _obj.type ? _obj.type: 'GET' ),
			url: ( _obj.url ? _obj.url : '/ajax.php' ),
			data: ( _obj.data ? _obj.data : 0 ),
			complete: ( _obj.complete ? _obj.complete : 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 = MODAL_DEF_OPT;
	if( typeof( opt2 ) == 'object' )
	{
		for( var i in opt2 )
		{
			opt[ i ] = opt2[ i ];
		}
	}
	$( '#poll-new' ).modal( opt );
}

function onNewPollCategoryChanged()
{
	var cat = $( '#category' )[0];
	$( '.poll-subcat' ).hide().attr( 'disabled', 1 );
	$( '#subcat_' + cat.options[ cat.selectedIndex ].getAttribute( 'uid' ) ).show().removeAttr( 'disabled' );
}

var newPoll = {};
function savePollData()
{
	newPoll.name = $( '#poll-new-name' ).val();
	newPoll.question = $( '#poll-new-question' ).val();
	newPoll.cat = $( '#category' ).val();
	newPoll.sub = $( '#poll-td-sub select:visible' ).val();
	newPoll.options = $( '#poll-new-options' ).val();
}

function restorePollData()
{
	$( '#poll-new-name' ).val( newPoll.name );
	$( '#poll-new-question' ).val( newPoll.question );
	$( '#poll-new-options' ).val( newPoll.options );
	$( '#category' ).val( newPoll.cat );
	onNewPollCategoryChanged();
	$( '#poll-td-sub select:visible' ).val( newPoll.sub );
}

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

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

function genId()
{
	var d = new Date();
	return( d.getTime() );
}

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();

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

			if( created )
			{
				// add option to categories list
				var cat = $( '#category' )[ 0 ];
				var catId = genId();

				var opt = new Option( newCat, newCat );
				opt.setAttribute( 'uid', catId );
				cat.options.add( opt );
				cat.selectedIndex = cat.options.length - 1;

				// create subcategory list
				var sub = $( '<select>' );
				sub.attr({ id : 'subcat_' + catId,
							'class' : 'poll-subcat',
							name : 'subcategory'
						});

				var opt2 = new Option( newSub, newSub );
				sub[0].options.add( opt2 );
				sub.appendTo( '#poll-td-sub' );

				onNewPollCategoryChanged();
			}
		}
	});
}

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

	$.modal.close();

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

			if( created )
			{
				// add option to active subcategory list
				var sub = $( '#poll-td-sub select:visible' )[ 0 ];
				var opt = new Option( newSub, newSub );
				sub.options.add( opt );
				sub.selectedIndex = sub.options.length - 1;
			}
		}
	});
}

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' );
	ajaxRequest({
		'type' : 'POST',
		'data' : {
			'op' : 'new_poll',
			'name' : name,
			'question' : question,
			'category' : $( '#category' ).val(),
			'subcategory' : $( '.poll-subcat:visible' ).val(),
			'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 validateAnketa()
{
	$( '.error' ).hide();

	var e = $( '#EMAIL' ).val();
	var f = 0;
	if( e.length == 0 )
	{
		err( '#EMAIL', 'Пожалуйста, ввeдите Ваш E-mail адрес!' );
		f = 1;
	}

	if( !isValidEmail( e ) )
	{
		err( '#EMAIL', 'E-mail введeн неверно.  Пожалуйста, ввeдите Ваш E-mail адрес в формате: sasha@primer.ru' );
		f = 1;
	}

	var y = $( '#YEAR' ).val();
	if( y.length == 0 )
	{
		err( '#YEAR', 'Пожалуйста укажите Ваш год рождения' );
		f = 1;
	}
	if( y < 1900 || y > 2008 )
	{
		err( '#YEAR', 'Год рождения должен быть от 1900 до 2008' );
		f = 1;
	}

	var i = $( '#INDEKS' ).val();
	if( i.length == 0 )
	{
		err( '#INDEKS', 'Пожалуйста, введите правильный индекс!' );
		f = 1;
	}

	return( !f );
}

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();
}