// scripts-common.js for EES

var host = '';

var cat_name = '';
var item_id = 0;

jQuery.fn.reverse = [].reverse;

// XHR

function sendXHR( http_string, post_string, on_ready, on_error, obj ) {
	// Create an object
	var xhr;
	try { xhr = new ActiveXObject( 'Msxml2.XMLHTTP' ) }
	catch( e ) {
		try { xhr = new ActiveXObject( 'Microsoft.XMLHTTP' ) }
		catch( E ) { xhr = false }
	}
	if( !xhr && typeof XMLHttpRequest != 'undefined' ) { xhr = new XMLHttpRequest() }

	// Initiate the object
	if( post_string == null ) { xhr.open( 'GET', http_string, true ) }
	else { xhr.open( 'POST', http_string, true ) }
	xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
	xhr.setRequestHeader( 'X-Requested-With', 'XMLHttpRequest' );
	xhr.send( post_string );

	// Check readyState
	var xhrTimeOut = setTimeout( function() { xhr.abort(); on_error.call( null, xhr_timeout ) }, 10000 );
	var checkReady = function() {
		if( xhr.readyState == 4 ) {	
			clearTimeout( xhrTimeOut );
			if( xhr.status == 200 ) { on_ready.call( null, eval( '(' + xhr.responseText + ')' ), obj ) }
			else { on_error.call( null, xhr_error + xhr.status, obj ) }
		}
		else { setTimeout( checkReady, 10 ) }
	}
	setTimeout( checkReady, 10 )
};

// SETTING COOKIE

function setCookie( c_name, value, expiredays, path, domain ) {
	var expdate = new Date();
	expdate.setDate( expdate.getDate() + expiredays );
	document.cookie = c_name + "=" + escape( value ) +
		( ( expiredays == null ) ? "" : ";expires=" + expdate.toGMTString() ) +
		( ( path ) ? ";path=" + path : "" ) +
        ( ( domain ) ? ";domain=" + domain : "" );
}

// INSERTING FLASH

function insertFlash( node, url, width, height, params ) {
	var object, param, key;
	function newParam( name, value ) {
		if( 0 /*@cc_on + 1 @*/ ) return ['<param name="', name, '" value="', value, '" />'].join( '' );
		else {
			param = document.createElement( 'param' );
			param.name = name;
			param.value = value;
			return param;
		}
	}
	if( 0 /*@cc_on + 1 @*/ ){
		object = ['<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="', width, '" height="', height, '"><param name="movie" value="', url, '" />'];
		if(params){
			for( key in params ){
				if( params.hasOwnProperty( key ) ) {
					object.push( newParam( key, params[key] ) );
				}
			}
		}
		object.push( '</object>' );
		node.innerHTML = object.join( '' );
	}
	else {
		object = document.createElement( 'object' );
		object.type = 'application/x-shockwave-flash';
		object.data = url;
		object.width = width;
		object.height = height;
		if( params ){
			for( key in params ){
				if( params.hasOwnProperty( key ) ) {
					object.appendChild( newParam( key, params[key] ) );
				}
			}
		}
		while( node.firstChild ) { node.removeChild( node.firstChild ) };
		node.appendChild( object );
	}
};

// NAVIGATION IN PAGBOX

function navPrev( obj,len ) {
	var _jr = $( obj ).next().children();
	var left = parseInt( _jr.css( 'margin-left' ) );
	if( left + len <= 0 ) {
		var full_shift = left + len;
		_jr.animate( { marginLeft: full_shift + 'px' }, 333 );
	}
}
function navNext( obj,len ) {
	var _jr = $( obj ).prev().children();
	var w = parseInt( _jr.width() );
	var left = parseInt( _jr.css( 'margin-left' ) );
	if( left - len > -w ) {
		var full_shift = left - len;
		_jr.animate( { marginLeft: full_shift + 'px' }, 333 );
	}
}

// *****************************************************************************
// COMMENTS LIST
// *****************************************************************************

// PRINT SELECTED COMMENT

function print_comment( comm, can_del ) {
	// Print a "delete buttun"
	var del = can_del ? "<b i='" + comm['cid'] + "'>X</b>" : '';
	return "<div class='comm_bl'><div class='comm_ttl'><span class='comm_date_add'>" + comm['date_add'] + "&nbsp;&nbsp;|</span><span class='comm_user_name'>" + ( comm['name'] ? comm['name'] : comm['gname'] ) + "</span>" + del + "</div><p>" + comm['ctext'] + "</p></div>";
}

// ADD A COMMENT

var add_comm = function() {
	// Check input data
	var name = document.getElementById( 'comm_name' ).value;
	var ctext = document.getElementById( 'comm_ctext').value;
	var kkey = document.getElementById( 'comm_res' ).value;
	if( !jQuery.trim( name ) ) { return alert( 'Вы забыли представиться' ) }
	if( !jQuery.trim( ctext ) ) { return alert( 'Ваш комментарий?' ) }
	if( !jQuery.trim( kkey ) ) { return alert( 'Антиспамм код?' ) }

	// Remove click handler
	$( this ).unbind( 'click' );

	// Send request
	sendXHR( '/comments/add/' + cat_name + '/' + item_id, 'name=' + encodeURIComponent( name ) + '&ctext=' + encodeURIComponent( ctext ) + '&kkey=' + kkey, comm_add_ready, comm_add_error, {} );
}
var comm_add_ready = function( r, obj ) {
	// Success
	if( !r['error'] ) {
		// Clear random comment block if it exists (for video)
		$( '#rand_c' ).empty();

		// Update counter
		$( '#player_qc' ).text( 1 + parseInt( $( '#player_qc' ).text() ) );

		// Hide "ADD A COMMENT" form
		$( 'td.add_comm' ).animate( { opacity:0 }, { duration:444 } );

		// Send request to show comments
		sendXHR( '/comments/show/' + cat_name + '/' + item_id + '/1', '', comm_show_ready, comm_show_error, {} );
	}
	// Failure
	else {
		// Update antispamm code
		document.getElementById( 'comm_res_t' ).innerHTML = r['as'];

		// Show error message
		alert( r['msg'] );

		// Get back click handler
		$( '#comm_btn_send' ).click( add_comm );
	}
}
var comm_add_error = function( msg, obj ) {
	// Show error message
	alert( msg );

	// Get back click handler
	$( '#comm_btn_send' ).click( add_comm );
}

// SHOW COMMENTS' LIST

var comm_show_ready = function( r, obj ) {
	// Success
	if( !r['error'] ) {
		// Print comments' list'
		var c = '';
		for( var i in r['data'] ) {	c += print_comment( r['data'][i], r['candel'] )	}
		$( '#comm_bl' ).html( c );

		// Set handler for delete buttons
		$( '#comm_bl b[i]' ).click( function() { comm_del( this ) } )
	}
	// Failure
	else {}
}
var comm_show_error = function( msg, obj ) {}

// DELETE THE COMMENT

var comm_del = function( obj ) {
	if( !confirm( 'Вы действительно хотите удалить этот комментарий?' ) ) { return }
	sendXHR( '/comments/del/' + cat_name + '/' + item_id + '/' + obj.getAttribute( 'i' ), 'a=a', comm_del_ready, comm_del_error, obj )
}
var comm_del_ready = function( r, obj ) {
	// Success
	if( !r['error'] ) {
		var div = obj.parentNode.parentNode;
		div.parentNode.removeChild( div )
	}
	// Failure
	else {}
}
var comm_del_error = function( msg, obj ) { }

// OPENFLASH FOR 3D GALLERY
function openFlash( obj, w, h, id ){
	$( 'body' ).append( "<div class='y-wrapper' id='swf'></div><span id='swf-obj'></span><div id='swf-close'></div><div id='swf-descr'><div>" + document.getElementById( 'th' + id + 'info' ).innerHTML + "</div></div>" );
	var swf = document.getElementById( "swf-obj" );
	$(swf).css( {height:h + 'px', width:w+'px', marginTop:-Math.ceil(h/2) + 'px', marginLeft: -Math.ceil(w/2)+'px' } );
	$( '#swf-close' ).css( {marginTop: -15-Math.ceil(h/2)+'px', marginRight: -30-Math.ceil(w/2)+'px'} );
	$( '#swf-descr' ).css( {marginTop: Math.ceil(h/2)+30+'px'} );

	var parametrs = { allowfullscreen: "true", wmode: "opaque", quality: "high" };
	insertFlash( swf, obj.getAttribute('href'), w, h, parametrs );
	$('#swf-close').click( function(){
		$(swf).remove();
		$('#swf').remove();
		$(this).remove();
		$('#swf-descr').remove();
	} );
}

// ASK A QUESTION
var aaq_succ = function( r, obj ) {
	$( '#status-request' ).html( r['msg'] ).fadeIn( 222 );
	setTimeout( function(){ $( '#status-request' ).fadeOut( 222 ) }, 2000 );
	$( 'table.vcomm-add' ).fadeOut(666)
}
var aaq_fail = function( r, obj ){
	$( '#status-request' ).html( r['msg'] ).fadeIn( 222 );
	setTimeout( function(){ $( '#status-request' ).fadeOut( 222 ) }, 2000 )
}
function aaq( url ) {
	var name = document.getElementById( 'vcomm-name' ).value;
	var contact = document.getElementById( 'vcomm-cont' ).value;
	var comment = document.getElementById( 'vcomm-ctext' ).value;
	if( !trim(name) )		return	alert( 'Укажите, пожалуйста, как к Вам обращаться.' );
	if( !trim(contact) )	return	alert( 'Укажите свой контактный e-mail и/или телефон для связи' );
	if( !trim(comment) )	return 	alert( 'Ваши вопросы/комментарии?' );
	sendXHR( url,	'name=' + encodeURIComponent( name ) +
					'&contact=' + encodeURIComponent( contact ) +
					'&comment=' + encodeURIComponent( comment ), aaq_succ, aaq_fail, {} );
}

// *****************************************************************************
// ON READY
// *****************************************************************************

$( document ).ready( function() {

	// HOVER & CLICK ON "SHOW COMMENTS"
	
	$( '#comm_btn_show' ).hover(
		function() { $( this ).addClass( 'hov' ) },
		function() { $( this ).removeClass( 'hov' ) }
	).click( function() {
		
		// Clear random comment if exists
		$( '#rand_c' ).empty();

		// Send request to show comments
		sendXHR( '/comments/show/' + cat_name + '/' + item_id + '/1', 'a=a', comm_show_ready, comm_show_error, {} );
	} );


	// EMAIL CLICK IN FOOTER

	$( 'span.email' ).hover(
		function() { $( this ).addClass( 'hov' ) },
		function() { $( this ).removeClass( 'hov' ) }
	).click( function() { document.location.href = 'mailto:' + this.getAttribute( 'n1' ) + '@' + this.getAttribute( 'n2' ) } )
} )