$(document).ready(function() {
	$(document).keydown(function(e){
		if (e.keyCode == 27 && $('div.newsletterForm').is(':visible')) {
			closeNewsletterForm();
			e.preventDefault();
		}
	});
	$(document).click(function(){
		if (newsletterFormIsClosable == true) {
			closeNewsletterForm();
		}
	});
	$('div.newsletterForm').hover(function(e) {
		newsletterFormIsClosable = false;
	}, function(e) {
		newsletterFormIsClosable = true;
	});
	/*
	 * handler for the click event in the on the move ticker
	 */
	$('div.onthemoveTicker div.link').click(function() {
		location.href = $('div.onthemoveTicker div.link a').attr('href');
	})
});

/*
 * function for positioning the distinct hosting banner
 */
function positionDistinctHostingBanner() {
	var footerLeft = parseInt($('div.siteFooter').offset().left);
	var footerTop = parseInt($('div.siteFooter').offset().top);
	var footerWidth = $('div.siteFooter').width();
	var bannerTop = parseInt(footerTop - 45) + 'px';
	var bannerLeft = parseInt(footerLeft + footerWidth - 186) + 'px';
	$('div.distinctHostingBanner').css('top',bannerTop).css('left',bannerLeft);
}


/*
 * function for positioning the branding
 */
function positionBranding() {
	var windowWidth = $(window).width();
	if (windowWidth >= 1260) {
		/* positioning top branding div */
		$('#topBranding').css('left',Math.ceil((windowWidth - 1260) / 2) + 'px');
		$('#topBranding').css('width','1260px');
		/* positioning left branding div */
		$('#leftBranding').css('left',Math.ceil((windowWidth - 1260) / 2) + 'px');
		$('#leftBranding').css('width','135px');
		/* positioning right branding div */
		$('#rightBranding').css('left',Math.ceil(windowWidth - ((windowWidth - 1260) / 2) - 135) + 'px');
		$('#rightBranding').css('width','135px');
	} else {
		/* cropping and positioning top branding div */
		var cropWidth = parseInt((1260 - windowWidth) / 2);
		var topBrandingWidth = windowWidth < 990 ? parseInt(windowWidth + cropWidth + (990 - windowWidth)) : parseInt(windowWidth + cropWidth);
		/* positioning top branding div */
		$('#topBranding').css('left','-' + cropWidth + 'px');
		$('#topBranding').css('width',topBrandingWidth + 'px');
		/* positioning left branding div */
		$('#leftBranding').css('left','-' + cropWidth + 'px');
		/* positioning right branding div */
		var rightBrandingWidth = parseInt(135 - cropWidth) > 0 ? parseInt(135 - cropWidth) : 0;
		var rightBrandingLeft = parseInt(windowWidth - rightBrandingWidth);
		$('#rightBranding').css('width',rightBrandingWidth + 'px');
		$('#rightBranding').css('left',rightBrandingLeft + 'px');
	}
	$('#leftBranding').css('top',$('#topBranding').height() + 'px');
	$('#rightBranding').css('top',$('#topBranding').height() + 'px');
	$('#main').css('padding-top',$('#topBranding').height() + 'px');
}

/*
 * functions for opening/closing/submitting the newsletter subscribe form
 */
var newsletterFormIsClosable = true;
function openNewsletterForm(position) {
	if (position == 'high') {
		var newsletterFormButton = $('div.newsletter img').offset();
		$('div.newsletterForm').css('top',parseInt(newsletterFormButton.top + 25) + 'px').css('left',parseInt(newsletterFormButton.left + $('div.newsletter img').width() - $('div.newsletterForm').width()) + 'px');
		$('div.newsletterForm').fadeIn('slow');
	} else {
		var newsletterFormButton = $('div.shareLine a.newsletter').offset();
		$('div.newsletterForm').css('top',parseInt(newsletterFormButton.top + 21) + 'px').css('left',parseInt(newsletterFormButton.left) + 'px');
		$('div.newsletterForm').fadeIn('slow');
	}
}
function closeNewsletterForm() {
	$('div.newsletterForm').fadeOut('fast');
}
function submitNewsletterForm() {
	var emailAddress = $('div.newsletterForm input[name="email"]').val();
	var frequency = $('div.newsletterForm input[name="frequency"]').val();
	var currentContent = $('div.newsletterForm').html();
	$('div.newsletterForm').html('<div class="loading" style="width: 310px;">Va rugam asteptati.</div>');
	$.post(
		root + 'ajax.php',
		{
			'method' : 'newslettersubscribe', 
			'type' : frequency, 
			'email' : emailAddress
		},
		function(data) {
			if (data['result'] == 1) {
				$('div.newsletterForm').fadeOut('slow',function() {
					$('div.newsletterForm').html(currentContent);
					$('div.newsletterForm input[name=email]').val('');
					alert('Felicitari! Adresa dvs. de email a fost abonata la newsletterul DailyBusiness.');
				})
			} else {
				$('div.newsletterForm').html(currentContent);
				$('div.newsletterForm input[name=email]').val(emailAddress);
				alert(data['errString']);
			}
		},
		'json'
	);
}

/*
 * the following function fixes IE8's problem with form submission
 */
function submitTopSearchForm() {
	location.href = root + 'stiri-despre/' + encodeURIComponent($('#topKeyword').val()).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}
function submitBottomSearchForm() {
	location.href = root + 'stiri-despre/' + encodeURIComponent($('#bottomKeyword').val()).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}

/*
 * function for refreshing the exchange graph image
 */
function refreshExchangeGraph() {
	var firstCurrency = $('select[name=first]').val();
	var secondCurrency = $('select[name=second]').val();
	var period = $('select[name=period]').val();
	$('#currencyGraph').attr('src',root + 'exchangegraph.php?period=' + period + '&currency=' + firstCurrency + ',' + secondCurrency);
}

/*
 * function for hackign the display on top players
 */
function resizeTpTable() {
	var totalWidth = 0;
	$('div.tpTableHolder div.tpTable div.header').each(function() {
		totalWidth += $(this).outerWidth();
	})
	if ($.browser.msie) {
		$('div.tpTableHolder div.tpTable').css('width',parseInt(totalWidth + 1) + 'px');
	} else {
		$('div.tpTableHolder div.tpTable').css('width',parseInt(totalWidth) + 'px');
	}
}

/*
 * function for controlling the cursvalutar.dailybusiness.ro insert on the right
 */
function expandExchangeRate() {
	if ($('#exchangeRateLinks').is(':visible')) {
		$('#exchangeRateLinks').slideUp('slow');
		$('#expandExchangeRate').attr('class','downArrow');
	} else {
		$('#exchangeRateLinks').slideDown('slow');
		$('#expandExchangeRate').attr('class','upArrow');
	}
}

/*
 * function for positioning the header
 */
function moveSiteHeader() {
	var siteHeaderHTML = $('div.siteHeaderHolder').html();
	$('#main').prepend('<div class="siteHeader">' + siteHeaderHTML + '</div>');
	$('div.siteHeaderHolder').remove();
}

/*
 * function for displaying the hidden top players
 */
function expandTopPlayers(whichCategory) {
	$('#expandTopPlayers' + whichCategory).hide('slow',function() {
		$('#hiddenTopPlayers' + whichCategory).slideDown('slow');
	});
}

/*
 * function for toggling most read and most commented
 */
function toggleMostOfAll(whichElement) {
	if (whichElement == 'read') {
		var visibleContent = $('.mostRead').html();
		$('#mostReadLink').attr('class','on');
		$('#mostCommentedLink').attr('class','off');
	} else {
		var visibleContent = $('.mostCommented').html();
		$('#mostReadLink').attr('class','off');
		$('#mostCommentedLink').attr('class','on');
	}
	$('.mostOfAllContentHolder').html(visibleContent);
}

/*
 * function for exchange rates
 */
function doExchange() {
	var howMuch = parseFloat($('input[name=fromCurrencyValue]').val());
	var fromRate = parseFloat($('select[name=fromCurrencyRate]').val());
	var toRate = parseFloat($('select[name=toCurrencyRate]').val());
	var exchangeAmount = isNaN(howMuch) ? 0 : howMuch * fromRate / toRate;
	$('input[name=toCurrencyValue]').val(number_format(parseFloat(exchangeAmount),4,',','.'));
	var vatValue = exchangeAmount * 0.24;
	var totalValue = exchangeAmount + vatValue;
	$('#vatOnly').html(number_format(vatValue,2,',','.') + ' RON');
	$('#vatTotal').html(number_format(totalValue,2,',','.') + ' RON');
}

/*
 * functions for keypeople widget
 */
function kpExpandMembers(collapseOthers) {
	if (collapseOthers == true) {
		if ($('#kpDomainsList').is(':visible')) {
			$('#kpDomainsList').slideUp('fast',function() {
				$('#kpDomainsLink').attr('class','');
			});
		} else if ($('#kpForumsList').is(':visible')) {
			$('#kpForumsList').slideUp('fast',function() {
				$('#kpForumsLink').attr('class','');
			});
		}
	}
	if ($('#kpMembersList').is(':visible')) {
		$('#kpMembersList').slideUp('fast',function() {
			$('#kpMembersLink').attr('class','');
		});
	} else {
		$('#kpMembersList').slideDown('fast',function() {
			$('#kpMembersLink').attr('class','upArrow');
		});
	}
}

function kpExpandDomains(collapseOthers) {
	if (collapseOthers == true) {
		if ($('#kpMembersList').is(':visible')) {
			$('#kpMembersList').slideUp('fast',function() {
				$('#kpMembersLink').attr('class','');
			});
		} else if ($('#kpForumsList').is(':visible')) {
			$('#kpForumsList').slideUp('fast',function() {
				$('#kpForumsLink').attr('class','');
			});
		}
	}
	if ($('#kpDomainsList').is(':visible')) {
		$('#kpDomainsList').slideUp('fast',function() {
			$('#kpDomainsLink').attr('class','');
		});
	} else {
		$('#kpDomainsList').slideDown('fast',function() {
			$('#kpDomainsLink').attr('class','upArrow');
		});
	}
}

function kpExpandForum(collapseOthers) {
	if (collapseOthers == true) {
		if ($('#kpDomainsList').is(':visible')) {
			$('#kpDomainsList').slideUp('fast',function() {
				$('#kpDomainsLink').attr('class','');
			});
		} else if ($('#kpMembersList').is(':visible')) {
			$('#kpMembersList').slideUp('fast',function() {
				$('#kpMembersLink').attr('class','');
			});
		}
	}
	if ($('#kpForumsList').is(':visible')) {
		$('#kpForumsList').slideUp('fast',function() {
			$('#kpForumsLink').attr('class','');
		});
	} else {
		$('#kpForumsList').slideDown('fast',function() {
			$('#kpForumsLink').attr('class','upArrow');
		});
	}
}

/*
 * function for equalizing the height of all sections news boxes
 */
function equalizeAllSectionsNewsBoxes() {
	var highest = 0;
	$('ul.allSectionsNews').each(function() {
		highest = $(this).height() > highest ? $(this).height() : highest;
	})
	$('ul.allSectionsNewsCenter').each(function() {
		highest = $(this).height() > highest ? $(this).height() : highest;
	})
	$('ul.allSectionsNews').each(function() {
		$(this).css('height',highest + 'px');
	})
	$('ul.allSectionsNewsCenter').each(function() {
		$(this).css('height',highest + 'px');
	})
}

/*
 * function for correctly aligning the article image
 */
function sizeArticleImage() {
	$('.articleContent .content .image .sizer').each(function() {
		var imageWidth = parseInt($(this).find('img').width() + 2);
		if (imageWidth < 232) {
			var leftMargin = parseInt((232 - imageWidth) / 2);
			var rightMargin = 232 - imageWidth - leftMargin;
			$(this).find('img').css('margin-left',leftMargin + 'px').css('margin-right',rightMargin + 'px');
		}
	})
}

/*
 * function for opening photo gallery
 */
function openGallery(galleryId, imageId, openerChannel) {
	window.open(root + 'gallery.php?galleryId=' + galleryId + '&imageId=' + imageId + '&channel=' + openerChannel,null,'width=825, height=800, status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=1, scrollbars=1');
}

/*
 * function for opening and closing the comments form
 */
function toggleCommentsForm() {
	if ($('span.addCommentForm').is(':visible')) {
		$('span.addCommentForm').slideUp('slow',function() {
			$('div.addCommentLink a').html('[+] Adauga comentariul tau');
		});
	} else {
		$('span.addCommentForm').slideDown('slow',function() {
			$('div.addCommentLink a').html('[-] Inchide formularul');
		});
	}
}

/*
 * function for displaying comments pages
 */
function getComments(articleType,articleID,pageNumber) {
	location.href = '#comments';
	$('#commentItems').html('<div class="loading width635">Continutul se incarca. Va rugam asteptati.</div>');
	$.post(
		root + 'ajax.php',
		{
			'method' : 'getcomments', 
			'type' : articleType, 
			'articleid' : articleID, 
			'page' : pageNumber
		},
		function(data) {
			if (data['result'] == 1) {
				$('#commentItems').html(data['commentItems']);
				$('.pagesLine').html(data['pagesLine']);
			} else {
				alert(data['errString']);
			}
		},
		'json'
	);
}

/*
 * function for submitting the comments form
 */
function submitCommentForm(articleID,articleType) {
	$.post(
		root + 'ajax.php',
		{
			'method' : 'postcomment', 
			'type' : articleType, 
			'articleid' : articleID, 
			'notify' : $('#articleCommentsForm input[name=notify]').val(), 
			'content' : $('#articleCommentsForm textarea').val(),
			'author' : $('#articleCommentsForm input[name="author"]').val(),
			'email' : $('#articleCommentsForm input[name="email"]').val(),
			'url' : $('#articleCommentsForm input[name="url"]').val()
		},
		function(data) {
			if (data['result'] == 1) {
				$('#articleCommentsForm').slideUp('fast',function() {
					$('#articleCommentsForm textarea').val('Exprima-ti parerea...');
					$('#articleCommentsForm input[name="author"]').val('');
					$('#articleCommentsForm input[name="email"]').val('');
					$('#articleCommentsForm input[name="url"]').val('');
					$('div.addCommentLink a').html('[+] Adauga comentariul tau');
					alert('Comentariul tau a fost inregistrat si va aparea pe site dupa moderare. Iti multumim!');
				});
			} else {
				alert(data['errString']);
			}
		},
		'json'
	);
}

/*
 * function for incrementing the number of views for an item
 */
function incrementViews(articleID,articleType) {
	$.post(
		root + 'ajax.php',
		{
			'method' : 'incrementviews', 
			'type' : articleType, 
			'articleid' : articleID
		},
		function(data) {
			// just nothing
		},
		'json'
	);
}

/*
 * submitting the contact form
 */
function submitContactForm() {
	$('#contactForm').submit();
}

function trim(s) {
	try {
		var l = 0;
		var r = s.length - 1;
		while (l < s.length && s[l] == ' ') {
			l++;
		}
		while (r > l && s[r] == ' ') {
			r-= 1;
		}
		return s.substring(l, r+1);
	} catch(e) {
		return '';
	}
}

function number_format(a, b, c, d) {
	// number_format(number, decimals, comma, formatSeparator)
	a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
	e = a + '';
	f = e.split('.');
	if (!f[0]) f[0] = '0';
	if (!f[1]) f[1] = '';
	if (f[1].length < b) {
		g = f[1];
		for(i = f[1].length + 1; i <= b; i++) {
			g += '0';
		}
		f[1] = g;
	}
	if (d != '' && f[0].length > 3) {
		h = f[0];
		f[0] = '';
		for(j = 3; j < h.length; j += 3) {
			i = h.slice(h.length - j, h.length - j + 3);
			f[0] = d + i +  f[0] + '';
		}
		j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
		f[0] = j + f[0];
	}
	c = (b <= 0) ? '': c;
	return f[0] + c + f[1];
}

function myInteractiveBanner_DoFSCommand(command,args) {
	if (command == 'closeSiteSplitter') {
		$('#siteSplitter').css('height','85px');
	}
}
