﻿if( typeof( cBalkanTourist ) == 'undefined' )
{
	cBalkanTourist = new Object()
}

//cBalkanTourist.CS_RPC_SERVER_URL = 'http://balkan-tourist.com/server/balkantourist-server.php'
cBalkanTourist.CS_RPC_SERVER_URL = 'server/balkantourist-server.php'
cBalkanTourist.CS_RPC_SITE_SERVER_URL = 'balkantourist-site-rpc.php'
//cBalkanTourist.CS_RPC_SERVER_URL = '../server/balkantourist-server.php'

cBalkanTourist.sActiveUrl = ''

cBalkanTourist.aDayNames = { 0:"Неделя", 1:"Понеделник", 2:"Вторник", 3:"Сряда", 4:"Четвъртък", 5:"Петък", 6:"Събота" }

cBalkanTourist.parseTextDate = function( sDate )
{
	var hDateFormat = new cDateFormat( 'd.m.Y' )
	return hDateFormat.parse( sDate )
}

cBalkanTourist.trackTheOffer = function( sOfferId )
{
	var hMessage = new XMLRPCMessage( 'balaknTourist.trackOffer' )
	hMessage.onResponse = cBalkanTourist.onOfferTracked
	hMessage.addParameter( sOfferId )
	hMessage.send( cBalkanTourist.CS_RPC_SERVER_URL )
}

cBalkanTourist.onOfferTracked = function( hXMLRPCResponse )
{
	if( hXMLRPCResponse == null )
	{
	    alert( 'some error occured' )
	    return false
	}
	window.location.href = cBalkanTourist.sActiveUrl
}

cBalkanTourist.onOfferLinkClick = function( hEvent )
{
	var hOfferLink = getParentByTagName( this, 'A' )
	cBalkanTourist.sActiveUrl = hOfferLink.href
	var sOfferId = hOfferLink.getAttribute( 'offerid' )
	cBalkanTourist.trackTheOffer( sOfferId )
	cDomEvent.cancelEvent( hEvent )
	return false
}

cBalkanTourist.initOfferLink = function( hOfferBlock )
{
	cDomEvent.addEvent2( hOfferBlock, 'click', cBalkanTourist.onOfferLinkClick )
}

cDomExtensionManager.register( new cDomExtension( document, [ "a[id=offerLink]" ], cBalkanTourist.initOfferLink ) )

/* send the request to the server */
cBalkanTourist.bSendingRequest = false
cBalkanTourist.submitRequest = function()
{
	if( cBalkanTourist.bSendingRequest )
	{
		alert( 'В момента се изпраща запитване' )
	}
	var hMessage = new XMLRPCMessage( 'balaknTouristSite.submitRequest' )
	hMessage.onResponse = cBalkanTourist.onRequestSubmited
	hMessage.onFail = cBalkanTourist.onRequestSubmitFailed

	hMessage.addParameter( getAllNodeText( document.getElementById( 'theContactForm' ) ) )
	hMessage.send( cBalkanTourist.CS_RPC_SITE_SERVER_URL )
	cBalkanTourist.showWaitIndicator( true )
	cBalkanTourist.bSendingRequest = true
}

cBalkanTourist.onRequestSubmited = function( hXMLRPCResponse )
{
	document.getElementById( 'contactUsContent' ).style.display = 'none'
	document.getElementById( 'contactUsSent' ).style.display = 'block'
	cBalkanTourist.bSendingRequest = false
	cBalkanTourist.showWaitIndicator()
}

cBalkanTourist.onRequestSubmitFailed = function()
{
	cBalkanTourist.bSendingRequest = false
	cBalkanTourist.showWaitIndicator()
}

cBalkanTourist.onSubmitRequestClick = function( hEvent )
{
	cBalkanTourist.submitRequest()
	cDomEvent.cancelEvent( hEvent )
	return false
}

/* request the offers for the last week */
cBalkanTourist.hWeekOffers = null
cBalkanTourist.nCurrentOfferIndex = 0

cBalkanTourist.loadWeekOffers = function()
{
	var hDate = new Date()
	hDate.setDate( hDate.getDate() + 1 )
	var hStartDate = new Date()
	hStartDate.setDate( hStartDate.getDate() - hStartDate.getDay() )
	hStartDate.setHours( 0 )
	hStartDate.setMinutes( 0 )
	var hMessage = new XMLRPCMessage( 'balaknTourist.getOffersInInterval' )
	hMessage.onResponse = cBalkanTourist.onWeekOffersLoaded
	hMessage.onFail = cBalkanTourist.onWeekOffersFailed

	var nPhpStartDate = Math.round( hStartDate.getTime() / 1000 )
	var nPhpDate = Math.round( hDate.getTime() / 1000 )
	hMessage.addParameter( nPhpStartDate )
	hMessage.addParameter( nPhpDate )
	hMessage.send( cBalkanTourist.CS_RPC_SERVER_URL )
	cBalkanTourist.showWaitIndicator( true )
}

cBalkanTourist.onWeekOffersLoaded = function( hXMLRPCResponse )
{
	if( hXMLRPCResponse == null )
	{
	    return false
	}
	cBalkanTourist.hWeekOffers = hXMLRPCResponse.hResponse
	
	if( hXMLRPCResponse.hResponse.length == 0 )
	{
		
	}
	else
	{
		var hPlaceholder = document.getElementById( 'weekOfferListPlaceholder' )
		while( hPlaceholder.childNodes.length > 0 )
		{
			hPlaceholder.removeChild( hPlaceholder.childNodes[0] )
		}
		
		for( var nI = 0; nI < hXMLRPCResponse.hResponse.length; nI ++ )
		{
			cBalkanTourist.addWeekOffer( nI )
		}
	}
	
	
	cBalkanTourist.showWeekOffers()
	cBalkanTourist.showWaitIndicator()
}

cBalkanTourist.onWeekOffersFailed = function()
{
	cBalkanTourist.showWaitIndicator()
}

cBalkanTourist.addWeekOffer = function( nOfferIdx )
{
	var hOfferData = cBalkanTourist.hWeekOffers[ nOfferIdx ]
	var hOffersContainer = document.getElementById( 'weekOfferListPlaceholder' )
	
	var hOfferContainer = document.createElement( 'dl' )
	hOfferContainer.className = 'week'
	hOfferContainer.setAttribute( 'offerindex', nOfferIdx )
	var hOfferName = document.createElement( 'dd' )
	hOfferName.appendChild( document.createTextNode( hOfferData[ 'offer_name' ] ) )
	var hOfferDate = cBalkanTourist.parseTextDate( hOfferData[ 'offer_activation_date' ] )
	var hOfferDay = document.createElement( 'dt' )
	var hPrintDateFormat = new cDateFormat( 'j.n.Y' )

	hOfferDay.appendChild( document.createTextNode( cBalkanTourist.aDayNames[ hOfferDate.getDay() ] + ' ' + hPrintDateFormat.toString( hOfferDate ) ) )
	hOfferContainer.appendChild( hOfferDay )
	hOfferContainer.appendChild( hOfferName )
	hOffersContainer.appendChild( hOfferContainer )
	
	cDomEvent.addEvent2( hOfferContainer, 'mousemove', cBalkanTourist.onWeekOfferMove )
	cDomEvent.addEvent2( hOfferContainer, 'mouseout', cBalkanTourist.onWeekOfferOut )
	cDomEvent.addEvent2( hOfferContainer, 'click', cBalkanTourist.onWeekOfferClick )
}

/* actions */
cBalkanTourist.onWeekOfferMove = function( hEvent )
{
	var hContainer = getParentByTagName( this, 'DL' )
	hContainer.className += ' weekOver'
	var nIdx = hContainer.getAttribute( 'offerindex' )
	var hOfferData = cBalkanTourist.hWeekOffers[ nIdx ]
	cBalkanTourist.setOfferImage( hOfferData[ 'offer_imageurl' ] )
}

cBalkanTourist.onWeekOfferOut = function( hEvent )
{
	var hContainer = getParentByTagName( this, 'DL' )
	hContainer.className = 'week'
	if( this.tagName.toLowerCase() != 'dl' )
	{
		cDomEvent.cancelEvent( hEvent )
		return
	}
	var hOfferData = cBalkanTourist.hWeekOffers[ cBalkanTourist.nCurrentOfferIndex ]
	cBalkanTourist.setOfferImage( hOfferData[ 'offer_imageurl' ] )
}

cBalkanTourist.onWeekOfferClick = function( hEvent )
{
	var hContainer = getParentByTagName( this, 'DL' )
	var nIdx = hContainer.getAttribute( 'offerindex' )
	document.getElementById( 'weekoffers' ).setAttribute( 'area', 'day' )
	cBalkanTourist.showDayOffer( nIdx )
	cDomEvent.cancelEvent( hEvent )
	return false
}

cBalkanTourist.sLastImageUrl = ''
cBalkanTourist.setOfferImage = function( sImageUrl )
{
	if( cBalkanTourist.sLastImageUrl == sImageUrl )
	{
		return
	}
	cBalkanTourist.sLastImageUrl = sImageUrl
	cBalkanTourist.loadBufferImage( sImageUrl )
}

cBalkanTourist.setOfferTitle = function( sTitle, sCountryCode )
{
	var hOfferTitle = document.getElementById( 'offerTitle' )
	var hOfferName = document.getElementById( 'offerName' )
	hOfferName.innerHTML = sTitle
	hOfferTitle.className = 'offerName' + sCountryCode
}

cBalkanTourist.setOfferDescription = function( sDescription )
{
	var hOfferDescription = document.getElementById( 'offerDescription' )
	hOfferDescription.innerHTML = sDescription
}

cBalkanTourist.setOfferLink = function( sURL, sOfferId )
{
	var hOfferLink = document.getElementById( 'offerLink' )
	hOfferLink.href = sURL
	hOfferLink.setAttribute( 'offerid', sOfferId )
}

cBalkanTourist.showWeekOffers = function()
{
	var hButton = document.getElementById( 'weekoffers' )
	hButton.className = 'dayoffer'
	hButton.innerHTML = 'днес'
	var hDayOffer = document.getElementById( 'body' ).getElementsByTagName( 'dl' )[ 0 ]
	var hWeekOffers = document.getElementById( 'body' ).getElementsByTagName( 'dl' )[ 1 ]
	hDayOffer.style.display = 'none'
	hWeekOffers.style.display = 'block'
}

cBalkanTourist.showDayOffer = function( nOfferIdx )
{
	if( cBalkanTourist.nCurrentOfferIndex == nOfferIdx )
	{
	}
	else
	{
		cBalkanTourist.nCurrentOfferIndex = nOfferIdx
		var hOfferData = cBalkanTourist.hWeekOffers[ cBalkanTourist.nCurrentOfferIndex ]
		cBalkanTourist.setOfferImage( hOfferData[ 'offer_imageurl' ] )
		cBalkanTourist.setOfferTitle( hOfferData[ 'offer_name' ], hOfferData[ 'offer_countrycode' ] )
		cBalkanTourist.setOfferDescription( textile( hOfferData[ 'offer_description' ] ) )
		cBalkanTourist.setOfferLink( hOfferData[ 'offer_url' ], hOfferData[ 'offer_id' ] )
	}

	var hButton = document.getElementById( 'weekoffers' )
	hButton.className = ''
	hButton.innerHTML = 'седмица'
	var hDayOffer = document.getElementById( 'body' ).getElementsByTagName( 'dl' )[ 0 ]
	var hWeekOffers = document.getElementById( 'body' ).getElementsByTagName( 'dl' )[ 1 ]
	hWeekOffers.style.display = 'none'
	hDayOffer.style.display = 'block'
}

/* init interface */
cBalkanTourist.showWaitIndicator = function( bShow )
{
	document.getElementById( 'indicator' ).style.visibility = ( bShow == true ) ? 'visible' : 'hidden'
}

cBalkanTourist.onWeekOffersClick = function( hEvent )
{
	if( this.getAttribute( 'area' ) && this.getAttribute( 'area' ) == 'week' )
	{
		this.setAttribute( 'area', 'day' )
		this.href='#today'
		cBalkanTourist.showDayOffer( 0 )
	}
	else
	{
		this.setAttribute( 'area', 'week' )
		this.href='#weekoffers'
		if( cBalkanTourist.hWeekOffers != null )
		{
			cBalkanTourist.showWeekOffers()
		}
		else
		{
			cBalkanTourist.loadWeekOffers()
		}
	}
}

cBalkanTourist.onAboutUsClick = function( hEvent )
{
	var hDayOffer = document.getElementById( 'body' ).getElementsByTagName( 'dl' )[ 0 ]
	var hWeekOffers = document.getElementById( 'body' ).getElementsByTagName( 'dl' )[ 1 ]
	hWeekOffers.style.display = 'none'
	hDayOffer.style.display = 'none'

	document.getElementById( 'contactUsContent' ).style.display = 'none'
	document.getElementById( 'aboutUsContent' ).style.display = 'block'

	document.getElementById( 'contactus' ).style.display = 'none'
	document.getElementById( 'aboutus' ).style.display = 'none'
	document.getElementById( 'weekoffers' ).style.display = 'none'
	document.getElementById( 'backtocontent' ).style.display = 'block'	
}

cBalkanTourist.onContactUsClick = function( hEvent )
{
	var hDayOffer = document.getElementById( 'body' ).getElementsByTagName( 'dl' )[ 0 ]
	var hWeekOffers = document.getElementById( 'body' ).getElementsByTagName( 'dl' )[ 1 ]
	hWeekOffers.style.display = 'none'
	hDayOffer.style.display = 'none'

	document.getElementById( 'aboutUsContent' ).style.display = 'none'
	document.getElementById( 'contactUsContent' ).style.display = 'block'

	document.getElementById( 'contactus' ).style.display = 'none'
	document.getElementById( 'aboutus' ).style.display = 'none'
	document.getElementById( 'weekoffers' ).style.display = 'none'
	document.getElementById( 'backtocontent' ).style.display = 'block'
}

cBalkanTourist.onBackToContentClick = function( hEvent )
{
	document.getElementById( 'contactus' ).style.display = 'block'
	document.getElementById( 'aboutus' ).style.display = 'block'
	document.getElementById( 'weekoffers' ).style.display = 'block'
	document.getElementById( 'backtocontent' ).style.display = 'none'

	document.getElementById( 'aboutUsContent' ).style.display = 'none'
	document.getElementById( 'contactUsContent' ).style.display = 'none'
	document.getElementById( 'contactUsSent' ).style.display = 'none'

	cBalkanTourist.showDayOffer( 0 )
}

cBalkanTourist.initInterfaceButtons = function( hButton )
{
	if( hButton.id == 'weekoffers' )
	{
		cDomEvent.addEvent2( hButton, 'click', cBalkanTourist.onWeekOffersClick )
	}
	if( hButton.id == 'aboutus' )
	{
		cDomEvent.addEvent2( hButton, 'click', cBalkanTourist.onAboutUsClick )
	}
	if( hButton.id == 'contactus' )
	{
		cDomEvent.addEvent2( hButton, 'click', cBalkanTourist.onContactUsClick )
	}
	if( hButton.id == 'backtocontent' )
	{
		cDomEvent.addEvent2( hButton, 'click', cBalkanTourist.onBackToContentClick )
	}
	if( hButton.id == 'submitRequest' )
	{
		cDomEvent.addEvent2( hButton, 'click', cBalkanTourist.onSubmitRequestClick )
	}
}

cDomExtensionManager.register( new cDomExtension( document, [ "a[class=buttons]" ], cBalkanTourist.initInterfaceButtons ) )

/* buffer image */
cBalkanTourist.initBufferImage = function()
{
	var hImage = document.createElement( 'img' )
	hImage.id = 'bufferImage'
	hImage.style.display = 'none'
	document.body.appendChild( hImage )
	hImage.onload = cBalkanTourist.onBufferImageLoaded
}

cBalkanTourist.onBufferImageLoaded = function( hEvent )
{
	var hImageBlock = document.getElementById( 'offerImage' )
	hImageBlock.style.backgroundImage = 'url(' + document.getElementById( 'bufferImage' ).src + ')'
}

cBalkanTourist.loadBufferImage = function( sUrl )
{
	var hImageBlock = document.getElementById( 'offerImage' )
	hImageBlock.style.backgroundImage = 'url(../i/indicator.gif)'
	var hBufferImage = document.getElementById( 'bufferImage' )
	hBufferImage.src = sUrl
}

/* contact form  */
cAutoEdit.onEndEdit = function( hContext )
{
	if( hContext.item.id == 'numberOfPeople' )
	{
		cBalkanTourist.onEndEdit( hContext )
	}
	else
	{
		cBalkanTourist.onEndEditBlock( hContext )
	}
	if( hContext.item.className.indexOf( 'edited' ) < 0 )
	{
		if( !hContext.cancel )
		{
			hContext.item.className += ' edited'
		}
	}
}

cBalkanTourist.onEndEdit = function( hContext )
{
	cFader.fadeOut( hContext.item.id )
	if( parseInt( hContext.input.value ) == 1 )
	{
		document.getElementById( 'peopleIndicator' ).replaceChild( document.createTextNode( 'човек' ), document.getElementById( 'peopleIndicator' ).childNodes[ 0 ] )
		document.getElementById( 'travelIndicator' ).replaceChild( document.createTextNode( 'пътува' ), document.getElementById( 'travelIndicator' ).childNodes[ 0 ] )
	}
	else
	{
		document.getElementById( 'peopleIndicator' ).replaceChild( document.createTextNode( 'души' ), document.getElementById( 'peopleIndicator' ).childNodes[ 0 ] )
		document.getElementById( 'travelIndicator' ).replaceChild( document.createTextNode( 'пътуват' ), document.getElementById( 'travelIndicator' ).childNodes[ 0 ] )
	}
}

cBalkanTourist.onEndEditBlock = function( hContext )
{
	cFader.fadeOut( hContext.item.id )
}

cBalkanTourist.typeOfInformationClick = function( hEvent )
{
	document.getElementById( 'typeOfInformation' ).innerHTML = this.innerHTML
	if( document.getElementById( 'typeOfInformation' ).className.indexOf( 'edited' ) < 0 )
	{
		document.getElementById( 'typeOfInformation' ).className += ' edited'
	}
	cFader.fadeOut( 'typeOfInformation' )
	cMoMenu.hideMenu()
}

cBalkanTourist.initMenuItems = function( hItem )
{
	cDomEvent.addEvent2( hItem, 'click', cBalkanTourist.typeOfInformationClick )
}

cDomExtensionManager.register( new cDomExtension( 'chooseMenu', [ "a" ], cBalkanTourist.initMenuItems ) ) 


cBalkanTourist.countryClick = function( hEvent )
{
	document.getElementById( 'destination' ).innerHTML = this.innerHTML
	if( document.getElementById( 'destination' ).className.indexOf( 'edited' ) < 0 )
	{
		document.getElementById( 'destination' ).className += ' edited'
	}
	cFader.fadeOut( 'destination' )
	cMoMenu.hideMenu()
}

cBalkanTourist.initCountryMenuItems = function( hItem )
{
	cDomEvent.addEvent2( hItem, 'click', cBalkanTourist.countryClick )
}

cDomExtensionManager.register( new cDomExtension( 'chooseCountryMenu', [ "a" ], cBalkanTourist.initCountryMenuItems ) ) 

/* load configuration options */
cBalkanTourist.init = function()
{
	cBalkanTourist.initBufferImage()
}

cDomEvent.addEvent2( window, 'load', cBalkanTourist.init )

/* misc */
function textile(s) 
{
   var r = s;
    // quick tags first
    var qtags = [['\\*', 'strong'],
             ['\\?\\?', 'cite'],
             ['\\+', 'ins'],  //fixed
             ['~', 'sub'],   
             ['\\%', 'span'],   
             ['\\^', 'sup'], // me
             ['@', 'code']];
	var sAdd 
	var sRep
	var ttag
	var ttag
	var re
    for (var i=0;i<qtags.length;i++) 
	{

		ttag = qtags[i][0]; htag = qtags[i][1];
        re = new RegExp(ttag+'([\\{\\[]?)([^\\}\\]]*)([\\}\\]]?)\\b(.+?)'+ttag,'g');
		re.test( r )

		sAdd = ''

		sRep = '<'+htag+'>'+'$4'+'</'+htag+'>'

		if( RegExp.$1 == '{' )
		{
			sRep = '<'+htag+' style="$2">'+'$4'+'</'+htag+'>'
		}
		if( RegExp.$1 == '[' )
		{
			sRep = '<'+htag+' class="$2">'+'$4'+'</'+htag+'>'
		}
        r = r.replace(re,sRep);
    }
    // underscores count as part of a word, so do them separately
    re = new RegExp('\\b_(.+?)_\\b','g');
    r = r.replace(re,'<em>$1</em>');
	
	//jeff: so do dashes
    re = new RegExp('[\s\n]-(.+?)-[\s\n]','g');
    r = r.replace(re,'<del>$1</del>');

    // links
    re = new RegExp('"\\b(.+?)\\(\\b(.+?)\\b\\)":([^\\s]+)','g');
    r = r.replace(re,'<a href="$3" title="$2">$1</a>');
    re = new RegExp('"\\b(.+?)\\b":([^\\s]+)','g');
    r = r.replace(re,'<a href="$2">$1</a>');

    // images
    re = new RegExp('!\\b(.+?)\\(\\b(.+?)\\b\\)!','g');
    r = r.replace(re,'<img src="$1" alt="$2">');
    re = new RegExp('!\\b(.+?)\\b!','g');
    r = r.replace(re,'<img src="$1">');
    
    // block level formatting
	
		// Jeff's hack to show single line breaks as they should.
		// insert breaks - but you get some....stupid ones
	    re = new RegExp('(.*)\n([^#\*\n].*)','g');
	    r = r.replace(re,'$1<br />$2');
		// remove the stupid breaks.
	    re = new RegExp('\n<br />','g');
	    r = r.replace(re,'\n');
	
    lines = r.split('\n');
    nr = '';
    for (var i=0;i<lines.length;i++) {
        line = lines[i].replace(/\s*$/,'');
        changed = 0;
        if (line.search(/^\s*bq\.\s+/) != -1) { line = line.replace(/^\s*bq\.\s+/,'\t<blockquote>')+'</blockquote>'; changed = 1; }
		
		// jeff adds h#.
        if (line.search(/^\s*h[1-6]\.\s+/) != -1) { 
	    	re = new RegExp('h([1-6])\.(.+)','g');
	    	line = line.replace(re,'<h$1>$2</h$1>');
			changed = 1; 
		}
		
		if (line.search(/^\s*\*\s+/) != -1) { line = line.replace(/^\s*\*\s+/,'\t<liu>') + '</liu>'; changed = 1; } // * for bullet list; make up an liu tag to be fixed later
        if (line.search(/^\s*#\s+/) != -1) { line = line.replace(/^\s*#\s+/,'\t<lio>') + '</lio>'; changed = 1; } // # for numeric list; make up an lio tag to be fixed later
        if (!changed && (line.replace(/\s/g,'').length > 0)) line = '<p>'+line+'</p>';
        lines[i] = line + '\n';
    }
	
    // Second pass to do lists
    inlist = 0; 
	listtype = '';
    for (var i=0;i<lines.length;i++) {
        line = lines[i];
        if (inlist && listtype == 'ul' && !line.match(/^\t<liu/)) { line = '</ul>\n' + line; inlist = 0; }
        if (inlist && listtype == 'ol' && !line.match(/^\t<lio/)) { line = '</ol>\n' + line; inlist = 0; }
        if (!inlist && line.match(/^\t<liu/)) { line = '<ul>' + line; inlist = 1; listtype = 'ul'; }
        if (!inlist && line.match(/^\t<lio/)) { line = '<ol>' + line; inlist = 1; listtype = 'ol'; }
        lines[i] = line;
    }

    r = lines.join('\n');
	// jeff added : will correctly replace <li(o|u)> AND </li(o|u)>
    r = r.replace(/li[o|u]>/g,'li>');

    return r;
}