
/******************************************************************************
 *
 *	PROJECT: Flynax Classifieds Software
 *	VERSION: 4.X
 *	LICENSE: FL0M2SG681CQ - http://www.flynax.com/license-agreement.html
 *	PRODUCT: Pets Classifieds
 *	DOMAIN: pupsnshop.com
 *	FILE: LIB.JS
 *
 *	The software is a commercial product delivered under single, non-exclusive, 
 *	non-transferable license for one domain or IP address. Therefore distribution, 
 *	sale or transfer of the file in whole or in part without permission of Flynax 
 *	respective owners is considered to be illegal and breach of Flynax License End 
 *	User Agreement. 
 *
 *	You are not allowed to remove this information from the file without permission
 *	of Flynax respective owners.
 *
 *	Flynax Classifieds Software 2014 |  All copyrights reserved. 
 *
 *	http://www.flynax.com/
 *
 ******************************************************************************/

var currencyConverterClass = function(){
	/**
	* plugin configs
	**/
	this.config = new Array();
	
	/**
	* plugin phrases
	**/
	this.phrases = new Array();
	
	/**
	* currency rates
	**/
	this.rates = new Array();
	
	/**
	* currency abbr
	**/
	this.abbr = new Array();
	
	/**
	* first time load flag
	**/
	this.first = true;
	
	/**
	* featured first time load flag
	**/
	this.first_f = true;
	
	/**
	* reference to this object
	**/
	var self = this;

	/**
	* currency selector action handler
	**/
	this.boxActions = function(){
		var cyrConvDo = true;
		var timer = false;
		$('#curConv_code').change(function(){
			$('#curConv_loading').fadeIn();
			cyrConvDo = false;
			clearTimeout(timer);
			xajax_setCurrency($(this).val());
		});
		
		$('#curConv_code').click(function(){
			cyrConvDo = false;
		});
		
		$('#curConv_change').click(function(){
			cyrConvDo = true;
			$('#curConv_1').hide();
			$('#curConv_2').show();
			timer = setTimeout(function(){
				if ( cyrConvDo )
				{
					$('#curConv_2').hide();
					$('#curConv_1').show();
				}
			}, 10000);
		});
	}
	
	/**
	* convert currency
	**/
	this.convert = function(){
		/* return if user currency does not exist in imported rates */
		if ( !this.rates[this.config['currency']] )
			return;
		
		/* listing grid */
		var field_id = 'sf_field_([0-9]+)_'+this.config['field'];
		var style = this.config['show_flags'] ? 'background-image: url('+this.config['flags_dir']+this.config['currency'].toLowerCase()+'.png)' : '';
		var flag = this.config['show_flags'] ? ' flag' : '';
		var poss = this.config['position'] == 'after' ? '' : ' disp-block';
		var post_selector = '';
		
		$('#listings div.item').find(':regex(id, '+field_id+')').each(function(index){
			var item = false;
			switch( $(this).get(0).tagName.toLowerCase() ){
				case 'tr':
					post_selector = '';
					if ( $(this).find('td:last > a').length > 0 )
					{
						post_selector = ' > a';
					}
					
					if ( self.first )
					{
						item = trim($(this).find('td:last'+post_selector).html());
						$(this).find('td:last'+post_selector).html('');
						var first = '<label class="cc-original'+poss+'">'+item+'</label>';
						var second = '<label title="'+self.phrases['converted']+'" style="'+style+'" class="cc-converted'+flag+poss+'"></label>';
						$(this).find('td:last'+post_selector).append(self.config['position'] == 'above' ? second : first).append(self.config['position'] == 'above' ? first : second);
					}
					else
					{
						item = trim($(this).find('td:last'+post_selector+' label.cc-original').html());
						$(this).find('td:last'+post_selector+' label.cc-converted').attr('style', style);
					}
					break;
				case 'span':
					post_selector = $(this).find('> a').length > 0 ? $(this).find('> a') : $(this);
					
					if ( self.first )
					{
						item = trim($(post_selector).html());
						$(post_selector).html('');
						var first = '<label class="cc-original'+poss+'">'+item+'</label>';
						var second = '<label title="'+self.phrases['converted']+'" style="'+style+'" class="cc-converted'+flag+poss+'"></label>';
						$(post_selector).append(self.config['position'] == 'above' ? second : first).append(self.config['position'] == 'above' ? first : second);
					}
					else
					{
						item = trim($(post_selector).find('label.cc-original').html());
						$(post_selector).find('label.cc-converted').attr('style', style);
					}
					break;
			}
			
			var curLine = self.decodePrice(item);
			
			if ( curLine && curLine.key != self.config.currency && curLine.price  )
			{
				var curRate = self.inRange(curLine.currency);
				var curDollar = curLine.price/curRate;
				var findRate = self.inRange(self.config['currency'], true);
				var newPrice = curDollar*findRate;
				
				$(this).find('label.cc-converted').show().html(self.encodePrice(newPrice));
				$(this).find('label.cc-original').css('opacity', 0.7);
			}
			else
			{
				$(this).find('label.cc-converted').hide();
				$(this).find('label.cc-original').css('opacity', 1);
			}
		});
		
		/* featured listings grid */
		if ( this.config['featured'] )
		{
			field_id = 'flf_([0-9]+)_'+this.config['field'];
			post_selector = '';
			
			$('ul.featured li.item').find('ul > li:regex(id, '+field_id+')').each(function(index){
				var item = false;
				post_selector = $(this).find('> a').length > 0 ? $(this).find('> a') : $(this);
				
				if ( self.first_f )
				{
					item = trim($(post_selector).html());
					$(post_selector).html('');
					var first = '<label class="cc-original'+poss+'">'+item+'</label>';
					var second = '<label title="'+self.phrases['converted']+'" style="'+style+'" class="cc-converted'+flag+poss+'"></label>';
					$(post_selector).append(self.config['position'] == 'above' ? second : first).append(self.config['position'] == 'above' ? first : second);
				}
				else
				{
					item = trim($(post_selector).find('label.cc-original').html());
					$(post_selector).find('label.cc-converted').attr('style', style);
				}
				
				var curLine = self.decodePrice(item);
				
				if ( curLine && curLine.key != self.config.currency && curLine.price  )
				{
					var curRate = self.inRange(curLine.currency);
					var curDollar = curLine.price/curRate;
					var findRate = self.inRange(self.config['currency'], true);
					var newPrice = curDollar*findRate;
					
					$(this).find('label.cc-converted').show().html(self.encodePrice(newPrice));
					$(this).find('label.cc-original').css('opacity', 0.7);
				}
				else
				{
					$(this).find('label.cc-converted').hide();
					$(this).find('label.cc-original').css('opacity', 1);
				}
			});
			
			this.first_f = false;
		}
		
		/* listing details */
		$('td.details tr[id=df_field_'+this.config['field']+'] td:last').each(function(index){
			var item = false;
			if ( self.first )
			{
				item = trim($(this).html());
				$(this).html('');
				var first = '<label class="cc-original'+poss+'">'+item+'</label>';
				var second = '<label title="'+self.phrases['converted']+'" style="'+style+'" class="cc-converted'+flag+poss+'"></label>';
				$(this).append(self.config['position'] == 'above' ? second : first).append(self.config['position'] == 'above' ? first : second);
			}
			else
			{
				item = trim($(this).find('label.cc-original').html());
				$(this).find('label.cc-converted').attr('style', style);
			}
			
			var curLine = self.decodePrice(item);
			
			if ( curLine && curLine.key != self.config.currency && curLine.price  )
			{
				var curRate = self.inRange(curLine.currency);
				var curDollar = curLine.price/curRate;
				var findRate = self.inRange(self.config['currency'], true);
				var newPrice = curDollar*findRate;
				
				$(this).find('label.cc-converted').show().html(self.encodePrice(newPrice));
				$(this).find('label.cc-original').css('opacity', 0.7);
			}
			else
			{
				$(this).find('label.cc-converted').hide();
				$(this).find('label.cc-original').css('opacity', 1);
			}
		});
		
		this.first = false;
	}
	
	/**
	* convert currency for featured blocks
	**/
	this.convertFeatured = function(block_key){
		/* return if user currency does not exist in imported rates */
		if ( !this.rates[this.config['currency']] )
			return;
		
		/* listing grid */
		var field_id = 'sf_field_([0-9]+)_'+this.config['field'];
		var style = this.config['show_flags'] ? 'background-image: url('+this.config['flags_dir']+this.config['currency'].toLowerCase()+'.png)' : '';
		var flag = this.config['show_flags'] ? ' flag' : '';
		var poss = this.config['position'] == 'after' ? '' : ' disp-block';
		var post_selector = '';
		
		/* featured listings grid */
		if ( this.config['featured'] )
		{
			field_id = 'flf_([0-9]+)_'+this.config['field'];
			post_selector = '';
			
			$('#'+block_key+' ul.featured li.item').find('ul > li:regex(id, '+field_id+')').each(function(index){
				var item = false;
				post_selector = $(this).find('> a').length > 0 ? $(this).find('> a') : $(this);
				
				if ( self.first_f )
				{
					item = trim($(post_selector).html());
					$(post_selector).html('');
					var first = '<label class="cc-original'+poss+'">'+item+'</label>';
					var second = '<label title="'+self.phrases['converted']+'" style="'+style+'" class="cc-converted'+flag+poss+'"></label>';
					$(post_selector).append(self.config['position'] == 'above' ? second : first).append(self.config['position'] == 'above' ? first : second);
				}
				else
				{
					if($(post_selector).find('label.cc-original').length)
					{
						item = trim($(post_selector).find('label.cc-original').html());
						$(post_selector).find('label.cc-converted').attr('style', style);
					}
					else
					{
						item = trim($(post_selector).html());
						$(post_selector).html('');
						var first = '<label class="cc-original'+poss+'">'+item+'</label>';
						var second = '<label title="'+self.phrases['converted']+'" style="'+style+'" class="cc-converted'+flag+poss+'"></label>';
						$(post_selector).append(self.config['position'] == 'above' ? second : first).append(self.config['position'] == 'above' ? first : second);
					}
				}
				
				var curLine = self.decodePrice(item);
				
				if ( curLine && curLine.key != self.config.currency && curLine.price  )
				{
					var curRate = self.inRange(curLine.currency);
					var curDollar = curLine.price/curRate;
					var findRate = self.inRange(self.config['currency'], true);
					var newPrice = curDollar*findRate;
					
					$(this).find('label.cc-converted').show().html(self.encodePrice(newPrice));
					$(this).find('label.cc-original').css('opacity', 0.7);
				}
				else
				{
					$(this).find('label.cc-converted').hide();
					$(this).find('label.cc-original').css('opacity', 1);
				}
			});
			this.first_f = false;
		}
	}
	
	/**
	* is in range
	*
	* @param string val - requested value
	* @param bool keySearch - key search mode
	*
	**/
	this.inRange = function(val, keySearch){
		if ( !this.rates )
			return false;
		
		if ( keySearch )
		{
			return this.rates[val][0];
		}
		else
		{
			for (var i in this.rates)
			{
				if ( $.inArray(val, this.rates[i][1]) >= 0 )
				{
					return this.rates[i][0];
				}
			}
		}
		
		return false;
	}
	
	/**
	* encode price
	*
	* @param string str - requested string
	* @param bool currency - hide currency
	* @param bool currency - hide separator
	**/
	this.encodePrice = function(str, hide_currency, hide_separator){
		if ( !str )
			return false;
		
		str = str.toFixed(2);
	
		/* convert price to string */
		eval("var converted = '"+ str +"'");
		
		var index = converted.indexOf('.');
		var rest = this.config['show_cents'] ? '.00' : '';
		
		if ( index >= 0 )
		{
			rest = converted.substring(index);
			
			if ( rest == '.00' && !this.config['show_cents'] )
			{
				rest = '';
			}
			
			converted = converted.substring(0, index);
		}
		
		/* revers string */
		var res = '';
		if ( !hide_separator )
		{
			converted = converted.reverse();
			for(var i = 0; i < converted.length; i++)
			{
				var char = converted.charAt(i);
				res += char;
				var j = i+1;
				if ( j % 3 == 0 && j != converted.length )
				{
					res += this.config['price_delimiter'];
				}
			}
			converted = res.reverse();
		}
		if (hide_currency)
		{
			converted = converted+rest;
		}
		else
		{
			converted = this.rates[this.config['currency']][1][0]+' '+converted+rest;
		}
		converted = !this.config['show_flags'] && this.config['position'] == 'after' ? ' - '+ converted : converted;
		
		return converted;
	}
	
	/**
	* decode price
	*
	* @param string str - requested string
	**/
	this.decodePrice = function(str){
		if ( !str )
			return false;
			
		var out = new Array();
		out['currency'] = out['key'] = false;
		
		var patter = new RegExp('(<.*?>)', 'ig');
		str = trim(str.replace(patter, ''));
		
		/* parse currency */
		var pattern = '^([A-Za-z\\W]{1,3})?\\s*?([0-9\.\,\'\:\;\"]+)\\s*?([A-Za-z\\W]{1,3})?$';
		var matches = str.match(pattern);
		
		if ( !matches )
		{
			return false;
		}
		
		if (matches[1] || matches[3])
		{
			out['currency'] = matches[1] ? trim(matches[1]) : trim(matches[3].replace(',',''));
			out['currency'] = out['currency'].replace(',', '');
			for (var i in this.rates)
			{
				if ( $.inArray(out['currency'], this.rates[i][1]) >= 0 )
				{
					out['key'] = i;
				}
			}
			
			str = matches[2];
		}
		else
		{
			return false;
		}
		
		if ( this.config['price_delimiter'] != '' )
		{
			var s = new RegExp("\\"+this.config['price_delimiter'], 'gi');
			str = str.replace(s, '');
		}
		
		str = parseInt(str);
		
		out['price'] = str;
		
		return out;
	}
}

var currencyConverter = new currencyConverterClass();

jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ? 
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}

if ( typeof window.reverse != 'function' )
{
	String.prototype.reverse = function() {
	    var s = "";
	    var i = this.length;
	    while (i>0) {
	        s += this.substring(i-1,i);
	        i--;
	    }
	    return s;
	}
}

$(document).ready(function(){
	currencyConverter.convert();
});