$(document).ready(function(){

	$.changeLocationModal = function() {
		$('#location-change-link').bind('click', function() {	
			$.ajaxRequest('ajax/ajax-main/change-location','',$.callbackChangeLoaction, null);
		});				
	}
	
	$.callbackChangeLoaction = function(data) {
		if(data.result == 'success') {
			$('#location-change-modal').html(data.html);
			$('#changeLocationModal').show();
		}
	}
	
	$.submitChangeLocation = function() {
		cityId = $('#select-town-form select[name=select-town] option:selected').attr('value');
		if(parseInt(cityId)>0) $.cookie('_cityCh', cityId, { expires: 365, path: '/', domain: '.neogen.rs'});
		$('#changeLocationModal').remove();
		window.location = PUBLIC_URL + 'channel/city/'+cityId+'/?fromHeader=99';
	}
	
	$.changeLocationModal();
	
	$.topShowArchive = function() {
		$('#top-archive-link').bind('click', function() {
			$(this).hide();
			$('#top-archive').show();
			$('#top-archive').bind('change', $.topGoToArchive);	
		});
	}
	
	$.topGoToArchive = function() {
		year = $('#top-archive option:selected').attr('year');
		month = $('#top-archive option:selected').attr('month');
		if(parseInt(year)>0 && parseInt(month)>0) {
			top.location = PUBLIC_URL + 'top/archive/'+year+'/'+month+'/';
		} else {
			top.location = PUBLIC_URL + 'top';
		}
	}
	
	
	$.setBackgroudImage = function(){
		if(!$.ifixpng)return;
		$.ifixpng('http://img.ineogen.ro/neogen/other/pixel.gif');
		$('img.userProfileVipImage').ifixpng();
		$('img.userProfileStickerImage').ifixpng();
	}
	$.setBackgroudImage();
	
	$.getJsonArray = function(data){
		data = '('+data+')';
		return eval(data);
	}
	
	$.showExtraCategories = function(contenType) {
		data = $.getJsonArray($('#topMenuMoreCategories'+contenType).attr('param'));
		size = data.length;
		html = '';
		for(i = 0; i < size; i++) {
			html += '<li><a href="' + data[i].link + '">' + data[i].title + '</a></li>';
		}
		$('#topMenuMoreCategories'+contenType).html(html).show();
	}
	
	$.attachHeaderEvents = function() {
		var selNode;
	
		$('#topMenu .more').bind('mouseover', function() {
			$.showExtraCategories($(this).attr('contentType'));
		});
	
		$("#iconExit").mouseover(function(){
			$("#headerIconsTooltipExit").show();
		});

		$("#iconExit").mouseout(function(){
			$("#headerIconsTooltipExit").hide();
		});
		
		$("#topMenu li a").bind('mouseleave', function(){
			$('#topMenu .topMenuMoreCategories').hide();
		});
		
		
		if (document.getElementById) {
			
			navRoot = document.getElementById("topMenu");
		
			for (i=0; i<navRoot.childNodes.length; i++) {
				node = navRoot.childNodes[i];
				if(node.className == 'on') selNode = node;
			}
		
			for (i=0; i<navRoot.childNodes.length; i++) {
				node = navRoot.childNodes[i];
				if (node.nodeName=="LI") {
					node.onmouseover=function() {
						if(selNode && selNode != this) selNode.className = selNode.className.replace("on", "off");
						if(this.className=='on' || this.className == 'off') this.className+=" over";
				 	}
		
					node.onmouseout=function() {
						if(selNode && selNode != this) selNode.className = selNode.className.replace("off", "on");
						this.className=this.className.replace(" over", "");
				   	}
				   	
		   		}
		   	}
		}   		
	}

	
	$.setMenu = function(activ){
		var menu = $('#search-box-tabs').attr('data');
		menu = $.getJsonArray(menu);		
		for(var i=0;i < menu.length; i++){
			var id = menu[i];
			if(id==activ)continue;
			$('#search-button-'+id).removeClass('active').addClass('inactive');
			$('#search-box-'+id).hide();
		}
		$('#search-button-'+activ).removeClass('inactive').addClass('active');
		$('#search-box-'+activ).show();
	}
	
	$('table#search-box-tabs td').click(function(){
		var id = $(this).attr('data');
		$.setMenu(id);
	});

        /*LEFT MENU */
        /**** ICONS TOOLTIP MOUSE OVER/OUT */
        $('#left-menu ul.list>li:not(.sublist) .icons a:not(.empty)')
            .bind('mouseover', function(){
                var t = $(this).attr('tooltip');
                var p = $(this).offset();
                if ($('#left-menu-tooltip').length==0) {
                    $('<div id="left-menu-tooltip" class="black-tooltip"><div class="text">'+t+'</div><div class="arrow"><img src="http://img.ineogen.ro/neogen/uploader/arrow-down.png" /></div></div>')
                        .css({left:p.left-5, top:p.top-30})
                        .appendTo('html body')
                        .show();
                } else {
                    $('#left-menu-tooltip > div.text').html(t);
                    $('#left-menu-tooltip').css({left:p.left-5, top:p.top-30}).show();
                }
            })
            .bind('mouseout', function(){$('#left-menu-tooltip').hide();});

	$('.walletSelectVotingButton').click(function(){
		var packet = $(this).attr('pack');
		var user = $(this).attr('userid');
		
		$.ajaxRequest('apps/top/save-vote',{'pack':packet,'userId':user},function(data){
			if(data.response == 'success') {
				$('#mainContent').append(data.message);
				$('#popupBoxWalletPay').show();
				$.walletAtachControl();
			}
		});	
	});

	$('.walletSelectIncognitoButton').click(function(){
		var packet = $(this).attr('pack');
		
		$.ajaxRequest('apps/incognito/save-vote',{'pack':packet},function(data){
			if(data.response == 'success') {
				$('#mainContent').append(data.message);
				$('#popupBoxWalletPay').show();
				$.walletAtachControl();
			}
		});	
	});

	$('#buyVipBox').click(function(){
		$.ajaxRequest('apps/vip/save-vote',{},function(data){
			if(data.response == 'success') {
				$('#mainContent').append(data.message);
				$('#popupBoxWalletPay').show();
				$.walletAtachControl();
			}
		});	
	});
	
	$('.walletAnimatedGift').click(function(){
		var idGift = $(this).attr('value');
		$('#popupBoxWalletGiftShow_'+idGift).show();
	});


	$('#walletChangeIncognitoButton').click(function(){		
		$.ajaxRequest('apps/incognito/status',{},function(data){
			if(data.response == 'success') {
				if(data.message==0){
					$('#walletChangeIncognitoButton .w_green_button_2').html($('#walletChangeIncognitoButton').attr('on'));
				} else {
					$('#walletChangeIncognitoButton .w_green_button_2').html($('#walletChangeIncognitoButton').attr('off'));
				}
			}
		});	
	});

	$.attachStickerEvent = function(data){
		if(data.response !='success')return;
		$('#mainContent').append(data.message);
		$('#stickerSelect_btnsend').hide();
		$('#selectOrderStickerBack').hide();
		$('#stickerSelect').show();
		$('#selectOrderStickerBack').click(function(){
			$('#stickerSelect #stickerSample').hide();			
			$('#stickerSelect_btnsend').hide();
			$('#selectOrderStickerBack').hide();
			$('#stickerSelect #allSticker').show();
		});
		
		$('#stickerSelect img.stickerElement').click(function(){
			//alert();
			id = $(this).attr('data');
			$('#stickerUserSticker').attr('val',id);
			url = $('#stickerUserSticker').attr('data');
			var sticktype = $(this).attr('sticktype');	
			if(sticktype=='sponsored'){
				$('#stickerSampleRight .iconNEuro_1').hide();
				$('#stickerSampleRight .stickerWalletText').hide();
			} else {
				$('#stickerSampleRight .iconNEuro_1').show();
				$('#stickerSampleRight .stickerWalletText').show();
			}		
			$('#stickerSelect #allSticker').hide();
			$('#stickerSelect #stickerSample').show();			
			$('#stickerSelect_btnsend').show();
			$('#selectOrderStickerBack').show();
			$('#stickerUserSticker').attr('src',url+id+'.png');
		});
	};
	
	$.sendSticker = function(user){
		sticker = $('#stickerUserSticker').attr('val');
		privacy = $('#stickerSelect input:radio:checked').val();
		message = $('#stickerText').val();
		$.ajaxRequest('apps/sticker/send',{userId:user,stickerId:sticker,privacyId:privacy,mess:message},function(data){
			if(data.response!='success')return;
			if(data.message=='ok'){
				document.location = '';
				return;
			}
			$('#mainContent').append(data.message.html);
			$('#stickerSelect').remove();
			$('#popupBoxWalletPay').show();
			$.walletAtachControl();
		});		
	};
	
	$('#profileHeadRightLinkGift').click(function(){
		id = $('#profile').attr('data');
		$.attachGiftEvent(id);
	});

	$.attachGiftEvent = function(id){
		$.ajaxRequest('apps/gift/list',{userId:id},function(data){
			if(data.response!='success')return;
			$('#mainContent').append(data.message);
			$('#giftSelect').show();
			$('.popup_gift_table img').click(function(){
				$.selectGift($(this).parent());
			});
			$('.popup_gift_table span').click(function(){
				$.selectGift($(this).parent());
			});
			$('#giftMessageSelect').change(function(){
				if( $(this).val()==1){
					$('#messageGiftBody').val('');
					$('#messageGiftBody').html('');
					$('#messageGiftBody').show();
					$('#messageGiftBodyText').show();
					return;
				}
				$('#messageGiftBody').hide();
				$('#messageGiftBodyText').hide();
				if( $(this).val()==0)return;
				$('#messageGiftBody').val($('#giftMessageSelect option:selected').html());
				$('#messageGiftBody').html($('#giftMessageSelect option:selected').html());				
			});
		});
		return false;	
	};	
	
	$.selectGift = function(elem){
		var id;
		id = elem.attr('id');
		elem.children('input').attr('checked','checked');
	};
	
	$.sendGift = function(userid){
		var gift, privacy, messageType, message;
		gift = $('.popup_gift_table input:radio:checked').val();
		privacy = $('#giftPrivate input:radio:checked').val();
		messageType = $('#giftMessageSelect').val();
		message = $('#messageGiftBody').val();
		$.ajaxRequest('apps/gift/send',{userId:userid,giftId:gift,privacyId:privacy,messageSelected:messageType,mess:message},function(data){
			if(data.response!='success')return;
			$('#mainContent').append(data.message.html);
			$('#giftSelect').remove();
			$('#popupBoxWalletPay').show();
			$.walletAtachControl();
		});
	};
	
	$('.walletGiftContainerActionSend').click(function(){
		var id = $(this).attr('value');
		$.attachGiftEvent(id);
		return false;
	});	

	$('.walletGiftContainerActionDelete').click(function(){
		var id = $(this).attr('value');
		$.ajaxRequest('apps/gift/delete',{giftId:id},function(data){
			if(data.response!='success')return;
			$('#walletGiftContainer_'+id).remove();
		});
	});	

	$('.walletStickerContainerActionSend').click(function(){
		var id = $(this).attr('value');
		$.ajaxRequest('apps/sticker/list',{userId:id},function(data){
			$.attachStickerEvent(data);
		});
		return false;
	});	

	$('.walletStickerContainerActionDelete').click(function(){
		var id = $(this).attr('value');
		$.ajaxRequest('apps/gift/delete',{giftId:id},function(data){
			if(data.response!='success')return;
			$('#walletGiftContainer_'+id).remove();
		});
	});	

});

function implodeSubmenu(id) {
	$.cookie('_xpndm_', null, { expires: 365, path: '/', domain: '.neogen.rs'});
	$("#left-menu .list > li:not(.sublist):not(#"+id+")").each(function(idx, item){
		var tog = $(item).find('.icons .toggle:first');
		if (tog.length > 0) {
			var submenu = $(item).next('.sublist');
			var data = eval('('+tog.attr('data')+')');

			submenu.hide();
			tog.addClass('down').removeClass('up').attr('tooltip',data.down);
		}
	});
}

function toggleSubmenu(id) {
    var tog = $('#'+id+' .icons .toggle').first();
    var submenu = $('#'+id).next('.sublist');
    var data = eval('('+tog.attr('data')+')');
    var c = $.cookie('_xpndm_');
    var expandedMenus = (c!=null && c!='' ? c : '');
    var m = id.substr(5);

    if (tog.hasClass('up')) {
        submenu.hide();
        tog.addClass('down').removeClass('up').attr('tooltip',data.down);
        expandedMenus = m+'0';
    } else {
		implodeSubmenu(id);
        submenu.show();
        tog.addClass('up').removeClass('down').attr('tooltip',data.up);
        expandedMenus = m+'1';
    }

    $.cookie('_xpndm_', expandedMenus, { expires: 365, path: '/', domain: '.neogen.rs'});
}

function leftMenuTooltipShow(id) {
    var t = $('#'+id).attr('tooltip');
    var p = $('#'+id).offset();
    if ($('#left-menu-tooltip').length==0) {
        $('<div id="left-menu-tooltip" class="black-tooltip"><div class="text">'+t+'</div><div class="arrow"><img src="http://img.ineogen.ro/neogen/uploader/arrow-down.png" /></div></div>')
            .css({left:p.left-5, top:p.top-30})
            .appendTo('html body')
            .show();
    } else {
        $('#left-menu-tooltip > div.text').html(t);
        $('#left-menu-tooltip').show();
    }
}
function leftMenuTooltipHide() {$('#left-menu-tooltip').hide();}


(function ($) {
$.ajaxRequest  = function(url,data,successCallback,errorCallback){
	$.ajax({
		type: 'POST',			
		url: 'http://www.neogen.rs/' + url,
		data: data,
		dataType: 'json',
		success: function(data) {
			successCallback(data);
		},
		error: function(obj, status, e) {
			if(errorCallback)errorCallback();
		}
	});	
};

$.walletAtachControl = function(){
	$('#popupBoxWalletPay').show();
	$('#close_wallet_payment_box').click(function(){
		$('#wallet_payment_box').hide();
		$('#neobizz_pay_select').show();
	});
	$('#walletCardPaymentClose').click(function(){
		$('#walletCardPaymentBox').hide();
		$('#wallet_payment_box').show();
	});
	$('#neobizz_close_fortumo').click(function(){
		$('#neobizz_fortumo_form').hide();
		$('#neobizz_pay_select').show();
	});
	$('#neobizz_fortumo_send').click(function(){
		$('#popupBoxWalletPay').remove();
	});
	$('.walletSelectPacket').click(function() {
	 	wallet = $('body').Wallet();
	 	wallet.showOrderBoxDyn(this);
	});
	$('.walletSelectPacketWallet').click(function() {
		$.walletGetIdPayment(this);
	});
	$('#walletSendSms').click(function() {
	 	wallet = $('body').Wallet();
	 	wallet.validateCode(this);
	});
	$('#walletPayCard').click(function(){
		$("#wallet_payment_box").hide();
		wallet = $('body').Wallet();
		wallet.showCardPayment();
	});
	$('#walletCardPaymentSend').submit(function() {
		wallet = $('body').Wallet();
		if (wallet.checkCardpaymentData (this)) {
			setTimeout ($('#popupBoxWalletPay').remove(), 200);
			return true;
		} else return false;
		alert('Handler for .submit() called.');
		return false;
	});
	$('.w_confirm_button .span2').click(function() {
		data = $('#walletConfirmData').attr('data');
		data = eval('('+data+')');
		$.walletConfirm(data.id,data.idp,data.url);	
	});
	$('#neobizzFortumoSend').click(function(){
		document.location = '';
	});
	return;						
};

$.walletAlreadyPay = false;
$.walletCallbackFunction = false;
$.walletCallbackParam = false;

$.walletGetIdPayment = function(param){
	$.ajaxRequest('apps/wallet/get-pay-id',{},function(data){
		if(data.response == 'success') {
			$('#paymentId').val(data.message.id);
			$('#walletOrderValue').html('W'+data.message.id);
			wallet = $('body').Wallet();
	 		wallet.showOrderBoxDyn(param);			
		}
	});
};

$.walletConfirm = function(id, idp, next_url) {
	if($.walletAlreadyPay) return;
	$.walletAlreadyPay = true;
	$.ajaxRequest('apps/wallet/confirm',{'id':id,'idp':idp,'url':next_url},function(data){
		if(data.response == 'success') {
			$('#popupBoxWalletPay').remove();
			$.walletAlreadyPay = false;
			if (data.message) {
				$('body').append(data.message);
				$('#wallet-action-reply').show();
				var yCenter = Math.round($(window).height() / 2) + $(window).scrollTop();
	        	var boxH = Math.round($('#wallet-action-reply').height() / 2);
				$('#wallet-action-reply').css('top',(yCenter-boxH)+'px');
			}
		} else {
			alert(data.message);
			$('#popupBoxWalletPay').remove();
			$.walletAlreadyPay = false;
		}

		return;
	});
};

$.walletStatic = false;
$.fn.Wallet = function () {
	if($.walletStatic)return $.walletStatic;
	var self = this;
	$.walletStatic = this;
	this.processing = false;
	
	this.showOrderBoxDyn = function(item) {
		self.pack = eval ('('+ $(item).attr('data') +')');
		$('#neobizz_pay_select').hide();
		$('#packValue').html (self.pack.value);
		$('#wSmsText').html (self.pack.servicePrefix);
		$('#wSmsNr').html (self.pack.smsNr);
		$('#wSmsPrice').html (self.pack.price +' '+ self.pack.currency);
		if (self.pack.type != 'sms') {
			$('.wDescSmsNr').html (self.pack.smsNr);
			if (self.pack.card == 1) {
				$('#packValue2').html(self.pack.val);
				$('.walletPayOption').addClass('half');
				$('.walletCardPayment').show();
				$('.walletSmsPayment').hide();
			} else {
				$('.walletPayOption').removeClass('half');
				$('.walletCardPayment').hide();
				$('.walletSmsPayment').show();
			}
			$('#wallet_payment_box').show ();
		} else $('#neobizz_fortumo_form').show ();
		return true;
	};
	
	this.validateCode = function() {
		if (this.processing) return false;
		var paymentId = $('#paymentId').val();
		var code = $('#validationCode').val();
		if (!paymentId) {
			alert('payment error!');
			return false;
		}
		if (!code) {
			alert('Code not given!');
			return false;
		}
		this.processing = true;
		$.ajax({
			url: PUBLIC_URL+'apps/wallet/validate',
			type: 'POST',
			dataType: 'json',
			data: {paymentId: paymentId, code: code},
			success: function(transport) {
				if (!transport.error) {
					$('#validationCode').val('');
					$('#paymentId').val('');
					$('#paymentBox').hide();
					if (transport.reload) {
						window.location.reload();
					} else
					if (transport.nextUrl) {
						window.location.assign(transport.nextUrl);
					} else
					if (transport.message) {
						$('#popupBoxWalletPay').remove();
						$('body').append(transport.message);
						$('#wallet-action-reply').show();
					}
				} else {
					alert(transport.message);
				}
				self.processing = false;
			},
			error: function(obj, status, e) {
				alert('Network error');
				self.processing = false;
			}
		});
		return true;
	};
	
	this.showCardPayment = function () {
		$('#cardPackPrice').text (self.pack.price);
		$('#cardPackFinalPrice').text ((self.pack.price * $.exchange).toFixed(2));
		$('input[name="package"]').val (self.pack.idpay);
		$('input[name="payment"]').val (self.smsCode);
		$('input[name="title"]').val ('Servicii internet Neogen '+ self.pack.price +' euro');
		$('#walletCardPaymentBox').show ();
	};
	
	this.checkCardpaymentData = function (frm) {
		$('#walletCardPaymentErrorMessage').hide();
		var fields = [frm.firstname, frm.name, frm.cnp, frm.ci, frm.address, frm.cod_postal, frm.tel];
		var error = false;

		for (var i=0; i<7; i++) {
			var field = fields[i];
			field.value = field.value.trim ();
			if (field.value.length < 2) {
				error = true;
				field.focus();
				$('#walletCardPaymentErrorMessage').html ($.cardPaymentErrorMessages[i]);
				break;
			}
		}

		if (!error && frm.cityId.value < 1) {
			frm.cityId.focus();
			error = true;
			$('#walletCardPaymentErrorMessage').html ($.cardPaymentErrorMessages[7]);
		}

		if (!error && frm.cityId.value == 10 && frm.sectorId.value < 1) {
			frm.sectorId.focus();
			error = true;
			$('#walletCardPaymentErrorMessage').html ($.cardPaymentErrorMessages[8]);
		}

		if (error) {
			$('#walletCardPaymentErrorMessage').show();
			return false;
		}

		return true;
	}
	return this;
};

$.bindChannelEventTimer = false;
$.bindChannelEventData = false;
$.bindCurrentChannel = {channel:false,cityChannel:false,feedChannel:false};
$.bindChannelEvent = function(){
	if($('#menu_notification_link').length<1 && $('#channelId').length<1)return;
	$.bindChannelEventData = {
		channelId: $('#channelId').val(),
		eventId: $('#lastEventId').val(),
		firstEventId: $('#firstEventId').val(),
		eventFilter: $('#eventFilter').val(),
		cityChannel: $('#isCityChannel').val(),
		userChannel: $('#isUserChannel').val()
	};
	if($.bindChannelEventData['channelId']!=undefined && $.bindChannelEventData['firstEventId']!='no' && $.bindChannelEventData['userChannel']<1){
		if($.bindChannelEventData['cityChannel']>0){
			if($.bindChannelEventData['channelId'] == $('#channel_menu_id_city').attr('data'))$.bindCurrentChannel['cityChannel'] = true;
			else $.bindCurrentChannel['feedChannel'] = true;
		} else {
			$.bindCurrentChannel['channel'] = $.bindChannelEventData['channelId'];
		}
	}
	$.bindChannelEventTimer = setInterval("$.bindChannelEventReqest();",10000);
	window.onunload = $.bindChannelEventStop;
};	
$.getIntFromString = function(text){
	if(text==null)return 0;
	text = text.toString();
	if(text != null){
		text = text.match(/[\d\.]+/g);
		if(text instanceof Array && text.length>0)text = text[0];
		else text = 0;
	} else {
		text = 0;
	}
	return text;
};

$.getSecoundIntFromString = function(text){
	text = text.toString();
	if(text != null){
		text = text.match(/[\d\.]+/g);
		if(text instanceof Array && text.length>1)text = text[1];
		else text = 0;
	} else {
		text = 0;
	}
	return text;
};

$.bindNewFeedsEventSet = false;
$.bindNewFeedsEvent = function(){
	if($.bindNewFeedsEventSet)return;
	$.bindNewFeedsEventSet = true;
	$("#more-new-feeds-holder").click(function(){
		$('#action-new-loading').show();
		$.ajaxRequest('ajax/ajax-channel/get-feeds',$.bindChannelEventData,function(data){
			$('#action-new-loading').hide();
			if(data.response!="success")return;
			if(data.message.id<1)return;
			$(".feeds").prepend(data.message.html);
			listFeeds = $('.feeds .feed-item');
			for(i = 0;i < listFeeds.length; i++){
				idn = $(listFeeds[i]).attr('id');
				idn = $.getSecoundIntFromString(idn);
				if($.bindChannelEventData['firstEventId'] < idn)
				{
					try
					{
						$(listFeeds[i]).channelFeedItem();
					}
					catch(error){}
					
					continue;
				}
				break;
			}
//			$('.feeds .feed-item:lt('+(lastItem.index())+')').channelFeedItem();
			$('#more-new-feeds-holder').hide();
			$.bindChannelEventData['firstEventId'] = data.message.id;
			$('#more-new-feeds-holder-nr').html('0');
		},function(){
			$('#action-new-loading').hide();		
		});	
	});
}

$.windowActive = true; 
if(!$.browser.msie)
	$(window).focus(function(){
		$.windowActive = true;
	}).blur(function(){
		$.windowActive = false;
	});

$.bindChannelEventReqest = function(){ 
	if($.windowActive == false)return;
	$.ajaxRequest('ajax/ajax-channel/get-more-feeds',$.bindChannelEventData,function(data){
		if(data.response!="success")return;
		channel = data.message.menu.channel;
		for(i=0;i < channel.length;i++){
			if(channel[i].val < 1)continue;
			if(channel[i].id==$.bindCurrentChannel['channel'])continue;
			channelObj = $('#channel_menu_id_'+channel[i].id);
			val = channelObj.html();
			val = $.getIntFromString(val);
			val  =  parseInt(channel[i].val) - parseInt(val);
			if(val == 0)continue;
			if(channel[i].val>99)channelObj.html(' (99+)');
			else channelObj.html(' ('+channel[i].val+')');
			group = channelObj.parent().attr('dataGroup');
			channelObjGroup = $('#channel_menu_id_'+group);
			groupVal = channelObjGroup.html();
			if(groupVal == null)continue;
			groupVal = $.getIntFromString(groupVal);
			groupVal = parseInt(groupVal)+val;
			if(groupVal>99)channelObjGroup.html(' (99+)');
			else channelObjGroup.html(' ('+groupVal+')');
		}
		if(data.message.menu.special.feed>0)
			if($.bindCurrentChannel['feedChannel']!=true){
				if(data.message.menu.special.feed>99)$('#channel_menu_id_feed').html(' (99+)');
				else $('#channel_menu_id_feed').html(' ('+data.message.menu.special.feed+')');
			}
		if(data.message.menu.special.city.length) {
			var t = 0;
			$.each(data.message.menu.special.city, function(idx, o) {
				if (parseInt($.bindChannelEventData['channelId'])!=parseInt(o.id) && o.count>0) {
					val = $('#channel_menu_id_city_'+o.id).html();
					if(o.count>99) $('#channel_menu_id_city_'+o.id).html(' (99+)');
					else $('#channel_menu_id_city_'+o.id).html(' ('+o.count+')');
					t += parseInt(o.count);
				}
			});

			channelObjGroup = $('#channel_menu_id_orase');
			if (channelObjGroup) {
				if(t>99) channelObjGroup.html(' (99+)');
				else if (t>0) channelObjGroup.html(' ('+t+')');
				else channelObjGroup.html('');
			}


		}
		if(data.message.menu.special.special>0)	{
			if($('#eventFilter').val()!="cityEvents" && $('#eventFilter').val()!="")return;
			$('#more-new-feeds-holder').show();		
			if(data.message.menu.special.special > 1){
				$('#more-new-feeds-one').hide();
				$('#more-new-feeds-more').show();					
			} else {
				$('#more-new-feeds-one').show();
				$('#more-new-feeds-more').hide();					
			}
			$('#more-new-feeds-holder-nr').html(data.message.menu.special.special);
			$.bindNewFeedsEvent();
		}
			
	},function(){
	});
};

$.bindChannelEventStop = function(){
	if($('#menu_notification_link').length<1)return;
	clearTimeout($.bindChannelEventTimer);
};
$.fn.neogen = function() 
{
   	var self = this;
	this.initialize = function() 
	{
		
	}

	this.toggleDisplayLng = function()
	{
		$("#sellng").toggle(
			function(){
				$('#langs').css("display", "");
				$('#arrow').removeClass('arrowright');
				$('#arrow').addClass('arrowdown'); },
			function(){
				$('#langs').css('display', 'none');
				$('#arrow').removeClass('arrowdown');
				$('#arrow').addClass('arrowright'); }
		)
	}
	
	this.setLng = function(id)
	{
		var postVars = "";
		postVars += "&languageId="+id;
		
		$.post("http://www.neogen.rs/ajax/ajax-main/set-language", postVars, this.setLngCallback);
	}
	
	this.setLngCallback = function(response)
	{
		eval(response);
	}
	
	this.initializeBlueMenu = function()
	{
		// add onclick on every blue menu tab
		$('.blueMenu').children().click(
			function(){
				$(this).parent().children().removeClass('selected');
				$(this).addClass('selected');
				
				$('#'+$(this).attr('target')).load($(this).attr('show'));
			} )
		
		// set selected the first menu tab or what it should (after parsing the url)
		$('.blueMenu').children(':first-child').each(
			function(){
				$(this).addClass('selected');
				$('#'+$(this).attr('target')).load($(this).attr('show'));
			}
		)
	}
	
	this.popupChat = function()
	{
	}
	
	this.resizePic = function()
	{
		$('#ad-pictures img').each(
			function(){
				if($(this).attr('width') == 200) {
					$(this).attr('width', 172);
					half = Math.round((132 - Math.round($(this).attr('height') * 0.86)) / 2); 
					$(this).css('margin-top', half);	
				} else {
					 $(this).attr('height', 132);
				}	 
			}
		)
	}
	
	return this;
    
}})(jQuery);

function f5captcha (id, src) {
	$('#'+id).attr("src", src+'&'+Math.random());
}

//save client screen resolution
function saveClientRes() {
	if(screen.width > 0 && (document.cookie.length==0 || document.cookie.indexOf("_ures=") == -1)) {
		$.cookie('_ures', screen.width, { path: '/', domain: '.neogen.rs'});
	}	
}
// end save client screen resolution

// left login box
$('#menu-login-form input').keydown(function(e){
    if (e.keyCode == 13) {
        $(this).parents('form').submit();
        return false;
    }
});
// end left login box

// left search
function selectNeobizzCategories() {
    o = neobizzJSON[parseInt($('#neobizzCategories option:selected').val())];

    if(o == undefined) {
		$('#neobizzSubcategories').html('<option value="0" contentType="">-</option>');
		$('#neobizzType').val('');
		return;
	}
    var l = o.length; html='';
    for(var i=0;i < l;i++) html += '<option value="'+o[i].v+'" contentType="'+o[i].ct+'">'+o[i].t+'</option>';
    $('#neobizzSubcategories').html(html);
	$('#neobizzType').val($('#neobizzCategories option:selected').attr('contenttype'));
}

$(document).ready(function(){
	$.bindChannelEvent();
    
    $("img").bind("contextmenu",function(e){ return false; });
	if ($('#search-box-neobizz:visible').length>0) {
		var id = $('#neobizzSubcategories option:selected').val();
		selectNeobizzCategories();
		$('#neobizzSubcategories option[value="'+id+'"]').attr('selected', 'selected');
	}
    
});

// end left search


/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-07-21 18:44:59 -0500 (Sat, 21 Jul 2007) $
 * $Rev: 2446 $
 *
 * Version 2.1.1
 */
 
 $.fn.bgIframe = $.fn.bgiframe = function(s) {
	// This is only for IE6
	if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
		s = $.extend({
			top     : 'auto', // auto == .currentStyle.borderTopWidth
			left    : 'auto', // auto == .currentStyle.borderLeftWidth
			width   : 'auto', // auto == offsetWidth
			height  : 'auto', // auto == offsetHeight
			opacity : true,
			src     : 'javascript:false;'
		}, s || {});
		var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
		    html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
		               'style="display:block;position:absolute;z-index:-1;'+
			               (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
					       'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
					       'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
					       'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
					       'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
					'"/>';
		return this.each(function() {
			if ( $('> iframe.bgiframe', this).length == 0 )
				this.insertBefore( document.createElement(html), this.firstChild );
		});
	}
	return this;
};

$.extend({
URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;o=o.replace(/\+/g, '%20');
  while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
  t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
});
