// @author injecteer
var scrollTop = 0;

function makeDefaults() {
	$$( 'input').each( function( input ){
		if( 'geoSuggestion' != input.id && 'fuzzySearch' != input.id && 'j_username' != input.id && 'password' != input.type ) return
		input.observe( 'focus', function( e ){
			if( e.element().value == e.element().defaultValue ) e.element().value = '';
		});
		input.observe( 'blur', function( e ){
			if( !e.element().value ) e.element().value = e.element().defaultValue;
		});
	} );
}

document.observe( 'dom:loaded', makeDefaults );

function toggleMeta( button, chck ){
  var cb = document.getElementById( 'meta_' + chck )
  var meta = button.className.substring(button.className.indexOf(' '),button.className.length)
  if( cb.checked ){
    button.className = 'iconButton' + meta
    cb.checked = false
  }else{
    button.className = 'iconButtonPressed' + meta
    cb.checked = true
  }
}

function replaceImg( url, desc ){
  $('imgContainer').src = url
  $('imgDesc').innerHTML = desc
}

function selectedText( id ){
  var opts = document.getElementById( id ).options;
  for( var i = 0; i < opts.length; i++ ){
    if( opts[ i ].selected ) return opts[ i ].text
  }
}

var lastClickedStarId = 5;

function hilightStars( selectedStarId, clicked ){
  var selectedStar = $( selectedStarId );
  if( !selectedStar || !selectedStar.id ) return false;
  if( clicked ) lastClickedStarId = selectedStarId;
  selectedStar.removeClassName( 'star0' );
  selectedStar.addClassName( 'star1' );
  selectedStar.previousSiblings().each( function( star ){
	star.removeClassName( 'star0' );
	star.addClassName( 'star1' );
  } );
  selectedStar.nextSiblings().each( function( star ){
	star.removeClassName( 'star1' );
	star.addClassName( 'star0' );
  } );
}
 
function localized2html( e ){
  var localized = eval( "("+e.responseText+")" ); 
  $( 'nameContainer' ).update( localized.name );
  $( 'descriptionContainer' ).update( localized.description );
}

function validateLogin( form ){
  form = $( form );
  if( 0 < form.down( '#j_username' ).value.length && 0 < form.down( '#j_password' ).value.length ){
	new Ajax.Request( form.action, {
	  parameters:form.serialize() + '&ajax=true',
	  onSuccess:function(e){ document.location.reload() },
	  onFailure:function(e){ 
		  alert( e.responseText ); 
	  }
	});   
    return false;
  }
  alert( 'Enter something ffs!' );
  return false;
}

function loadCategories( val, service ){
	new Ajax.Updater( '_category', categorySelectURL, { parameters:{ key:val, service:service } } );
	new Ajax.Updater( '_metaTags', metaTagsSelectURL, { parameters:{ key:val, service:service } } );
}

function extendTextAreas(){
	$$( 'textarea[maxSize]' ).each( function( ta ){
		if( $( ta.id + '_warning' ) ) return;
		var maxSize = ta.readAttribute( 'maxSize' );
		var warning = new Element( 'div', { id:ta.id + '_warning' } ).update( '&nbsp;' );
		warning.addClassName( 'warning' );
		warning.setStyle( { left:( ta.getWidth() - 60 ) + 'px' } );
		ta.insert( { 'before':warning } );
		ta.observe( 'keyup', function( e ){
			if( 35 == e.keyCode || 36 == e.keyCode || 38 == e.keyCode
			   || ( 15 < e.keyCode && 19 > e.keyCode )  
			   || 37 == e.keyCode || 39 == e.keyCode || 27 == e.keyCode || 40 == e.keyCode ) return;

			warning.update( ( maxSize - e.element().value.length - 1 ) + ' / ' + maxSize );
			if( e.element().value.length >= maxSize - 11 ){
				e.element().style.backgroundColor = 'PeachPuff';
				if( maxSize - 1 <= e.element().value.length ){
					warning.update( '0 / ' + maxSize );
					warning.style.color = 'red';
					e.element().style.backgroundColor = 'lightgrey';
					e.element().value = e.element().value.substr( 0, maxSize - 1 );
					return false;
				}
			}else{
				warning.style.color = 'black';
				e.element().style.backgroundColor = 'white';
			}
		} );
	});
}

document.observe( 'dom:loaded', extendTextAreas );

var editorTextArea;

function insertAtCursor( txtArea, insertable, keepSelection ){
	txtArea = $( txtArea );
	txtArea.focus();
	textAreaScrollPosition = txtArea.scrollTop;

	if( 'undefined' == typeof keepSelection ) keepSelection = true;
    if( null != txtArea.createTextRange ){
    	var range = txtArea.createTextRange();
    	range.text = 'string' == typeof insertable ? insertable : insertable( range.text );
        range.move( 'character', 0 );
        if( keepSelection ) range.select();
    }else if( null != txtArea.selectionStart ){
    	var startPos = txtArea.selectionStart;
    	var endPos = txtArea.selectionEnd;
    	var replacement = 'string' == typeof insertable ? insertable : insertable( txtArea.value.substring( startPos, endPos ).strip() );
    	txtArea.value = txtArea.value.substring( 0, startPos ) + replacement + txtArea.value.substring( endPos );
    	txtArea.scrollTop = scrollTop;
    	if( keepSelection ) txtArea.setSelectionRange( startPos, startPos + replacement.length );
	}else{
		txtArea.value += 'string' == typeof insertable ? insertable : insertable();
	}
    txtArea.scrollTop = textAreaScrollPosition;
}

function quickQuotePost( head ){
	if( !editorTextArea ) return;
	var selection;
	if( window.getSelection ) selection = window.getSelection().toString();
	else if( document.getSelection ) selection = document.getSelection();
	else if( document.selection ) selection = document.selection.createRange().text;
	else return;
	if( !selection || 0 == selection.length ) return; 
	insertAtCursor( editorTextArea, function(sel){ return '[quote ' + head + ']' + selection + '[/quote]\n' } );
}

var sections = new Array( 'help', 'geo', 'pois', 'events', 'forum', 'tours', 'shortAds', 'articles', 'users', 'shopPOI' );

var sectionsRegexp = new RegExp( '/(' + sections.inject( '', function( acc, s ){ return acc + '|' + s; } ).substring( 1 ) + ')/' );

function stripeCompositeKey(){
	for( var arg = 0; arg < arguments.length; arg++ ){
		if( -1 < $( arguments[ arg ] ).value.indexOf( '-' ) ){
			$( arguments[ arg ] ).value=$( arguments[ arg ] ).value.replace( /\D*-(\d+).*/i, '$1' );
		}
	}
}

function submitLink( formName, url ){
	$(formName).action = url;
	$(formName).submit();
}

var lastId;

function loadParts( e ){
  e.stop();
  loadParts4Url( e.findElement( 'a' ).href );
}

function toParams( link ){
	var paramsPart; 
	for( var ix = 0; ix < sections.length; ix++ ){
		var pos = link.indexOf( '/' + sections[ ix ] );
		if( -1 < pos ){
			paramsPart = link.substr( pos + 1 ).split( '/' );
			break;
		}
	}
	var action = paramsPart[ 0 ];
	if( -1 < action.indexOf( '?' ) ) action = action.substr( 0, action.indexOf( '?' ) );
	var id = ( paramsPart[ 1 ] || '' );
	var p = { 'section':action, 'id':id };
	if( 1 < id.split( '\?' ).length ) p.id = id.split( '\?' )[ 0 ];
	p.path = paramsPart[ 2 ];
	lastId = p.id;
	var lp = link.toQueryParams();
	if( lp.menuOffset ) p.menuOffset = lp.menuOffset;
	if( lp.notag ) p.notag = lp.notag;
	return p;
}

function loadParts4Url( link ){
  var params = toParams( link );
  new Ajax.Request( renderMenuLink, {
	  onComplete:json2content,
	  parameters:params
  } );
  loadBody4Url( link );
}

function loadBody( e ){
	e.stop();
	var link = e.findElement( 'a' ).href;
	var params = toParams( link );
	loadBody4Url( link, params );
}

function loadBody4Url( link, params ){
	var params = toParams( link ); 
	$( 'bodySpinner' ).show();
	new Ajax.Updater( 'bodyContainer', link, {
		evalScripts:true, 
		parameters:{ 'asAjax':true },
		onComplete:function(){
			$( 'bodySpinner' ).hide();
			extendLinksAndPagination();
			myDynamicPopup.extendLinks();
			try{
				document.title = $( 'modifier' ).innerHTML;
			}catch( ee ){}
		}
	} );
}

function buildAspects( aspects, selectedAction ){
	var c = $( 'aspectContainer' );
	c.update();
	aspects.items.each( function( item ){ 
		var div = new Element( 'div' ).addClassName( 'item' );
		if( -1 < item.path.indexOf( selectedAction ) ) div.addClassName( 'selected' );
		var txt = '<b>' + item.name + '</b>';
		if( -1 < item.hitsCount ) txt += ': <span>' + item.hitsCount + '</span>';
		var a = new Element( 'a', { 'href':item.path } ).update( txt );
		//if renderMenuLink exist - load the aspect's content per AJAX
		if( 'undefined' != typeof renderMenuLink ) a.observe( 'click', loadParts );
		div.insert( new Element( 'div' ).addClassName( 'li' ) );
		div.insert( new Element( 'div' ).addClassName( 'ci' ).insert( a ) );
		div.insert( new Element( 'div' ).addClassName( 'ri' ) );
		c.insert( div );
	} );
}

function menuNavigation( e ){
	e.stop();
	var params = toParams( e.findElement( 'a' ).href );
	$( 'menuSpinner' ).show();
	new Ajax.Request( renderMenuLink, {
		parameters:params,
		onComplete:function( t ){
		  var parts = eval( "("+t.responseText+")" );
		  buildMenu( parts.menuGeo, 'menuGeoContainer' );
		}
	} );
}

function buildUrl( action, id, path, params ){
  var p = 'undefined' == typeof( params ) ? '' : params;
  var url = urlBase + action + '/' + (id ? id : '');
  if( null != path && 0 < path.length ) url += '/' + path;
  url += p;
  return url;
}

function insertMenuPagination( menu, container ){
	container = $( container );
	if( !menu && !menu.prev && !menu.next ) return;
	$A( new Array( menu.prev, menu.next ) ).each( function( p ){
		if( null == p ) return;
		var a = new Element( 'a', { 'href':buildUrl( menu.action, p.id, '', '?menuOffset=' + p.params.menuOffset ), 'class':(menu.next?'nextGeos':'prevGeos')} ).update(  );
		a.observe( 'click', menuNavigation );
		container.insert( a );
	} );
}

function buildMenu( menu, container ){
	$( 'menuSpinner' ).hide();
	container = $( container );
	container.update();
	if( !menu ) return;
	buildPath( menu.path, menu.action, container, 'menuGeoContainer' == container.id );
	var div = new Element( 'div' ).addClassName( 'tcas' );
	container.insert( div );
	menu.items.each( function( item ){
		var a = new Element( 'a', { 'href':buildUrl( menu.action, item.id, item.path ) } );
		var fontSize = Math.max( Math.floor( 3 * Math.log( item.hitsCount ) ), 12 );
		fontSize = Math.min( fontSize, 24 )
		a.style.fontSize = fontSize + 'px';
		a.update( item.name );
		a.observe( 'click', loadParts );
		div.insert( a );
	} );
	if( menu.tag ){
		var a = new Element( 'a', { 'href':buildUrl( menu.action, menu.path.last().id, null, '?notag=true' ) } );
		a.addClassName( 'moreGeos' ).update( allDistrictsLabel );
		a.observe( 'click', menuNavigation );
		container.insert( a );
	}else insertMenuPagination( menu, container );
}

function buildPath( path, action, container, showFlag ){
	var p = new Element( 'p' ).addClassName( 'crumbs' );
	container.insert( new Element( 'div' ).addClassName( 'crumbsWrap' ).insert( p ) );
	path.each( function( item ){
		p.insert( new Element( 'img', { 'src':urlBase + 'images/theme/cloudedPath.gif' } ) );
		p.insert( new Element( 'span' ).update( '&nbsp;' ) );
		p.insert( new Element( 'a', { 'href':buildUrl( action, item.id, item.path ) } ).update(
			( showFlag && null != item.id && 2 == item.id.indexOf( '-' ) && null == item.path 
					? '<img src="' + urlBase + 'images/icons/country_' + item.id.substring( 0, 2 ) + '.gif" title="' + item.name + '" alt="' + item.name + '"/>' 
					: item.name ) 
		).observe( 'click', loadParts ) );
		p.insert( new Element( 'span' ).update( '&nbsp;' ) );
	});
	p.highlight( { duration:2, startcolor:'#FFCC00', endcolor:'#c3c3c3' } );
}

function json2content( transport ){
  var parts = eval( "("+transport.responseText+")" );
  buildMenu( parts.menuGeo, 'menuGeoContainer' );
  if( parts.menu && 'object' == typeof parts.menu ) buildMenu( parts.menu, 'menuContainer' );
  else $( 'menuContainer' ).update( parts.menu );
  buildAspects( parts.aspects, parts.menuGeo.action );
}

function serializeFilters() {
	$( 'additionalFilterSrc' ).select( 'input[type=checkbox]' ).each( function(checkbox) {
		document.forms['filterForm'].insert(checkbox);
		checkbox.hide();
	});
	$( 'additionalFilterSrc' ).hide();
	$( 'bodySpinner' ).show();
	var link = document.forms['filterForm'].action;
	new Ajax.Updater('bodyContainer', link, {
		evalScripts:true, 
		parameters :document.forms['filterForm'].serialize(),
		onComplete : function() {
			$('bodySpinner').hide();
			extendLinksAndPagination();
			myDynamicPopup.extendLinks();
		}
	});
	return false;
}

function extendLinksAndPagination(){
  $$( 'a[rel=menuLink]' ).invoke( 'observe', 'click', loadParts );
  $$( 'div.paginateButtons a', 'a[rel=bodyLink]' ).invoke( 'observe', 'click', loadBody );
  $$( 'a[rel=menuNavLink]' ).invoke( 'observe', 'click', menuNavigation );  
}
