/** On load events */
$(window).load(function(){
	$(document).pngFix();
	$('a').focus(function(){
		$(this).blur();
	});
	
	
	$('#header-menu ul.menu li:last').attr('style',"background-image:none");
	$('#header-menu ul.login li:last').attr('style',"background-image:none");
});

/** Standard */
$(function(){				
	$(".group-more").click( function(){
		$(".group-short-info", '#newsgroups').toggleClass("displaynone");
		$(".group-long-info", '#newsgroups').toggleClass("displaynone");
	});
	$('.text-column', '#container').columnize({width:440});
	
	/* lightbox */
	$("a[rel^='lightbox']").colorbox({onComplete:function() { incrementMultimediaViews() }});
	$("a[rel^='lightboxslideshow']").colorbox({slideshow:true,onComplete:function() { incrementMultimediaViews() }});
	$("a.lightbox").colorbox({onComplete:function() { incrementMultimediaViews() }});
	$(".lightbox-form").colorbox({transition:'none', initialWidth:494, initialHeight: 300, scrolling:false});
	$(".lightbox-iframe").colorbox({iframe:true, innerWidth:425, innerHeight:344, onComplete:function() { incrementMultimediaViews() }});
	
	/* calendar start */
		/* tab */
	$('#calendar-tabs div').hide();
	$('#calendar-tabs div:first').fadeIn().find('div').show().find('div.displaynone').hide();
	
	$('#main-page-calendar #calendar-switch a').bind('click', function(){
		var $this = $(this);
		var tab = $this.attr('href');

		$('#calendar-switch a').removeClass('selected');
		$this.addClass('selected');
		
		$('#calendar-tabs div').hide();
		$(tab).show().find('div').show().find('div.displaynone').hide();
		
		return false;
	});
		/* end tab */
		
	/* calendar img */
	var $img = $('.calendar-img img:first', '#calendar-tabs');
		$img.hide();
		
		if( $img.attr('src') != '' ) {
			$img.fadeIn();
		}
	
	/* calendar end */
	
	/* images hover */
	$('.garageImgHover').bind('mouseenter mouseleave', function(){
		if($('.garageImgHover p').hasClass("garage-over")){
			$('.garageImgHover p').removeClass("garage-over");
			$(".garageImgHover p").animate({
		        opacity: 0.5
		      }, 1500 );
		} else {
			$('.garageImgHover p').addClass("garage-over");
			$(".garageImgHover p").animate({
		        opacity: 0.8
		      }, 1500 );
		}
	});
	
	$(".tabbed").tabs();
	
	$("#gray").treeview({
		control: "#treecontrol",
		persist: "cookie",
		cookieId: "classics_treeview_menu"
	});
	
	$(".calendar-event", '#container').bind('mouseout mouseover', function(){
		id = $(this).attr('id');
		dates = id.split('-');
		from_date = dates[0];
		to_date = dates[1];
		for( ds = from_date ; ds <= to_date ; ds++ ){
			$("#d" + ds).toggleClass('sday');
		}
	});
	
	$('.toolbar-type', '#header-logo').bind('click', function(){
		var id = $(this).attr('id');
		
		$.post(ajax_url +'/change-toolbar/'+ id, function(data){
			if(data.toString() == 1) {
				window.location.reload();
			} else {
				alert('Could not change toolbar');	
			}
		});
		
		return false;
	});
});

function changeCalendarPhoto( id, module ) {
	if( $('.calendar-module-'+ module +' div img#calendar-photo-' + id).length != 0 ) {
		var $img	= $('.calendar-module-'+ module +' div img#calendar-photo-' + id);
		var src 	= $img.attr('src');
		var title 	= $img.attr('title');
		
		var str = src.toString().match(/\.(jpg|jpeg|gif|png)$/i);
		
		if( src != '' && str ) {
			$('.calendar-module-'+ module +' img:first').hide().attr('src', src). attr('title', title).show();
		} else {
			$('.calendar-module-'+ module +' img:first').hide();
		}
	} else {
		$('.calendar-module-'+ module +' img:first').hide();
	}
}

function incrementMultimediaViews () {
	var element = $.fn.colorbox.element();
	var id = element[0];
	id = id.toString().split('?');
	
	if(id[0] != 'undefined') {
		$.post( ajax_url +'/increment-multimedia-views/', {multimedia_id:id[1]} );
	}
}

function reloadUrlInto (url, where) {
	$.get(url,	function(data) {
		$(where).html(data);
	});
}

function cAlert( text, type, apppendTo, preserve ) {
	$(apppendTo).jAlert(text, type);
	if(!preserve) {
		$('.msg-box-cont').delay(2000).fadeOut(600);
	}
}

function showHide( obj ) {
	obj = document.getElementById( obj );
	obj.style.display == 'none' ? obj.style.display = '' : obj.style.display = 'none';
	
	obj = obj.previousSibling.previousSibling;
	obj.className == 'accordion_title_expanded' ? obj.className = 'accordion_title' : obj.className = 'accordion_title_expanded';
}

function showAll( objgroup, amount ) {
	for( i = 1 ; i <= amount ; i++ ) {
		obj = objgroup + '_' + i.toString();
		obj = document.getElementById(obj);
		
		if( obj ) {
			obj.style.display == 'none' ? obj.style.display = '' : obj.style.display = 'none'; 
			
			obj = obj.previousSibling.previousSibling;
			obj.className == 'accordion_title_expanded' ? obj.className = 'accordion_title' : obj.className = 'accordion_title_expanded';
		}
	}
}

function expAccordion( group1name,group1amount, group2name,group2amount ) {
	showAll( group1name, group1amount )
	showAll( group2name, group2amount );
}
	
function loadCitiesForAdsByProvinceId( pid, cid, lang ) {
	if( pid == null ) {
		var provId = $('#search_province :selected').val();
	} else {
		var provId = pid;
	}
	
	var $element = $("#search_city");
	$element.attr('disabled', 'true').children().remove().end().append('<option value="">' + lang + '</option>');
	
	$.getJSON( ajax_url + "/cities/?province=" + provId,
    function(data){
    	if (data) {
			$.each(data, function(i,item){
				$("<option></option>").text(item.city_name).val(item.city_id).appendTo("#search_city");
				
				if( cid == null ) {
					$element.attr('disabled', '');
				} else {
					$element.attr('disabled', '').val( cid );
				}	
			});
    	}
    });
}
	
function loadCitiesForAdsByCountryId( pid, cid, lang ) {
	if( pid == null ) {
		var provId = $('#search_country :selected').val();
	} else {
		var provId = pid;
	}
	
	var $element = $("#search_city");
	$element.attr('disabled', 'true').children().remove().end().append('<option value="">' + lang + '</option>');
	
	$.getJSON( ajax_url + "/cities/?country=" + provId,
    function(data){
    	if (data) {
			$.each(data, function(i,item){
				$("<option></option>").text(item.city_name).val(item.city_id).appendTo("#search_city");
				
				if( cid == null ) {
					$element.attr('disabled', '');
				} else {
					$element.attr('disabled', '').val( cid );
				}	
			});
    	}
    });
}

/*
 * Image preview script 
 * powered by jQuery (http://www.jquery.com)
 * 
 * written by Alen Grakalic (http://cssglobe.com)
 * 
 * for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 *
 */
 
this.imagePreview = function(){	
	/* CONFIG */
		
		xOffset = 10;
		yOffset = 30;
		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
		
	/* END CONFIG */
	$("img.preview").hover(function(e){
		this.t = this.title;
		this.title = "";	
		var c = (this.t != "") ? "<br/>" + this.t : "";
		$("body").append("<p id='preview'><img src='"+ this.src +"' alt='"+ this.alt +"' />"+ c +"</p>");								 
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");						
    },
	function(){
		this.title = this.t;	
		$("#preview").remove();
    });	
	$("img.preview").mousemove(function(e){
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};


// starting the script on page load
$(function(){
	imagePreview();
});

//
function initialize() {}

function strip_tags ( input, allowed ) {
// Strips HTML and PHP tags from a string  
// 
// version: 1009.2513
// discuss at: http://phpjs.org/functions/strip_tags
// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// +   improved by: Luke Godfrey
// +      input by: Pul
// +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// +   bugfixed by: Onno Marsman
// +      input by: Alex
// +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// +      input by: Marc Palau
// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// +      input by: Brett Zamir (http://brett-zamir.me)
// +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// +   bugfixed by: Eric Nagel
// +      input by: Bobby Drake
// +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// +   bugfixed by: Tomasz Wesolowski
// +      input by: Evertjan Garretsen
// +    revised by: Rafał Kukawski (http://blog.kukawski.pl/)
// *     example 1: strip_tags('<p>Kevin</p> <b>van</b> <i>Zonneveld</i>', '<i><b>');
// *     returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
// *     example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
// *     returns 2: '<p>Kevin van Zonneveld</p>'
// *     example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
// *     returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'
// *     example 4: strip_tags('1 < 5 5 > 1');
// *     returns 4: '1 < 5 5 > 1'
// *     example 5: strip_tags('1 <br/> 1');
// *     returns 5: '1  1'
// *     example 6: strip_tags('1 <br/> 1', '<br>');
// *     returns 6: '1  1'
// *     example 7: strip_tags('1 <br/> 1', '<br><br/>');
// *     returns 7: '1 <br/> 1'
   allowed = (((allowed || "") + "")
      .toLowerCase()
      .match(/<[a-z][a-z0-9]*>/g) || [])
      .join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
   var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
       commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
   return input.replace(commentsAndPhpTags, '').replace(tags, function($0, $1){
      return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
   });
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie=function(b,j,m){if(typeof j!="undefined"){m=m||{};if(j===null){j="";m.expires=-1}var e="";if(m.expires&&(typeof m.expires=="number"||m.expires.toUTCString)){var f;if(typeof m.expires=="number"){f=new Date();f.setTime(f.getTime()+(m.expires*24*60*60*1000))}else{f=m.expires}e="; expires="+f.toUTCString()}var l=m.path?"; path="+m.path:"";var g=m.domain?"; domain="+m.domain:"";var a=m.secure?"; secure":"";document.cookie=[b,"=",encodeURIComponent(j),e,l,g,a].join("")}else{var d=null;if(document.cookie&&document.cookie!=""){var k=document.cookie.split(";");for(var h=0;h<k.length;h++){var c=jQuery.trim(k[h]);if(c.substring(0,b.length+1)==(b+"=")){d=decodeURIComponent(c.substring(b.length+1));break}}}return d}};;/*
/*
 * Treeview 1.4 - jQuery plugin to hide and show branches of a tree
 * 
 * http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
 * http://docs.jquery.com/Plugins/Treeview
 *
 * Copyright (c) 2007 JĂ¶rn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.treeview.js 4684 2008-02-07 19:08:06Z joern.zaefferer $
 *
 */
(function($){$.extend($.fn,{swapClass:function(c1,c2){var c1Elements=this.filter('.'+c1);this.filter('.'+c2).removeClass(c2).addClass(c1);c1Elements.removeClass(c1).addClass(c2);return this;},replaceClass:function(c1,c2){return this.filter('.'+c1).removeClass(c1).addClass(c2).end();},hoverClass:function(className){className=className||"hover";return this.hover(function(){$(this).addClass(className);},function(){$(this).removeClass(className);});},heightToggle:function(animated,callback){animated?this.animate({height:"toggle"},animated,callback):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();if(callback)callback.apply(this,arguments);});},heightHide:function(animated,callback){if(animated){this.animate({height:"hide"},animated,callback);}else{this.hide();if(callback)this.each(callback);}},prepareBranches:function(settings){if(!settings.prerendered){this.filter(":last-child:not(ul)").addClass(CLASSES.last);this.filter((settings.collapsed?"":"."+CLASSES.closed)+":not(."+CLASSES.open+")").find(">ul").hide();}return this.filter(":has(>ul)");},applyClasses:function(settings,toggler){this.filter(":has(>ul):not(:has(>a))").find(">span").click(function(event){toggler.apply($(this).next());}).add($("a",this)).hoverClass();if(!settings.prerendered){this.filter(":has(>ul:hidden)").addClass(CLASSES.expandable).replaceClass(CLASSES.last,CLASSES.lastExpandable);this.not(":has(>ul:hidden)").addClass(CLASSES.collapsable).replaceClass(CLASSES.last,CLASSES.lastCollapsable);this.prepend("<div class=\""+CLASSES.hitarea+"\"/>").find("div."+CLASSES.hitarea).each(function(){var classes="";$.each($(this).parent().attr("class").split(" "),function(){classes+=this+"-hitarea ";});$(this).addClass(classes);});}this.find("div."+CLASSES.hitarea).click(toggler);},treeview:function(settings){settings=$.extend({cookieId:"treeview"},settings);if(settings.add){return this.trigger("add",[settings.add]);}if(settings.toggle){var callback=settings.toggle;settings.toggle=function(){return callback.apply($(this).parent()[0],arguments);};}function treeController(tree,control){function handler(filter){return function(){toggler.apply($("div."+CLASSES.hitarea,tree).filter(function(){return filter?$(this).parent("."+filter).length:true;}));return false;};}$("a:eq(0)",control).click(handler(CLASSES.collapsable));$("a:eq(1)",control).click(handler(CLASSES.expandable));$("a:eq(2)",control).click(handler());}function toggler(){$(this).parent().find(">.hitarea").swapClass(CLASSES.collapsableHitarea,CLASSES.expandableHitarea).swapClass(CLASSES.lastCollapsableHitarea,CLASSES.lastExpandableHitarea).end().swapClass(CLASSES.collapsable,CLASSES.expandable).swapClass(CLASSES.lastCollapsable,CLASSES.lastExpandable).find(">ul").heightToggle(settings.animated,settings.toggle);if(settings.unique){$(this).parent().siblings().find(">.hitarea").replaceClass(CLASSES.collapsableHitarea,CLASSES.expandableHitarea).replaceClass(CLASSES.lastCollapsableHitarea,CLASSES.lastExpandableHitarea).end().replaceClass(CLASSES.collapsable,CLASSES.expandable).replaceClass(CLASSES.lastCollapsable,CLASSES.lastExpandable).find(">ul").heightHide(settings.animated,settings.toggle);}}function serialize(){function binary(arg){return arg?1:0;}var data=[];branches.each(function(i,e){data[i]=$(e).is(":has(>ul:visible)")?1:0;});$.cookie(settings.cookieId,data.join(""));}function deserialize(){var stored=$.cookie(settings.cookieId);if(stored){var data=stored.split("");branches.each(function(i,e){$(e).find(">ul")[parseInt(data[i])?"show":"hide"]();});}}this.addClass("treeview");var branches=this.find("li").prepareBranches(settings);switch(settings.persist){case"cookie":var toggleCallback=settings.toggle;settings.toggle=function(){serialize();if(toggleCallback){toggleCallback.apply(this,arguments);}};deserialize();break;case"location":var current=this.find("a").filter(function(){return this.href.toLowerCase()==location.href.toLowerCase();});if(current.length){current.addClass("selected").parents("ul, li").add(current.next()).show();}break;}branches.applyClasses(settings,toggler);if(settings.control){treeController(this,settings.control);$(settings.control).show();}return this.bind("add",function(event,branches){$(branches).prev().removeClass(CLASSES.last).removeClass(CLASSES.lastCollapsable).removeClass(CLASSES.lastExpandable).find(">.hitarea").removeClass(CLASSES.lastCollapsableHitarea).removeClass(CLASSES.lastExpandableHitarea);$(branches).find("li").andSelf().prepareBranches(settings).applyClasses(settings,toggler);});}});var CLASSES=$.fn.treeview.classes={open:"open",closed:"closed",expandable:"expandable",expandableHitarea:"expandable-hitarea",lastExpandableHitarea:"lastExpandable-hitarea",collapsable:"collapsable",collapsableHitarea:"collapsable-hitarea",lastCollapsableHitarea:"lastCollapsable-hitarea",lastCollapsable:"lastCollapsable",lastExpandable:"lastExpandable",last:"last",hitarea:"hitarea"};$.fn.Treeview=$.fn.treeview;})(jQuery);;
/*
Elastic textarea

*/
(function(a){a.fn.extend({elastic:function(){var b=["paddingTop","paddingRight","paddingBottom","paddingLeft","fontSize","lineHeight","fontFamily","width","fontWeight"];return this.each(function(){if(this.type!="textarea"){return false}var g=a(this),c=a("<div />").css({position:"absolute",display:"none","word-wrap":"break-word"}),h=parseInt(g.css("line-height"),10)||parseInt(g.css("font-size"),"10"),k=parseInt(g.css("height"),10)||h*3,j=parseInt(g.css("max-height"),10)||Number.MAX_VALUE,d=0,f=0;if(j<0){j=Number.MAX_VALUE}c.appendTo(g.parent());var f=b.length;while(f--){c.css(b[f].toString(),g.css(b[f].toString()))}function l(i,m){curratedHeight=Math.floor(parseInt(i,10));if(g.height()!=curratedHeight){g.css({height:curratedHeight+"px",overflow:m});$(".changeHeight").css({height:curratedHeight+"px"})}}function e(){var n=g.val().replace(/&/g,"&amp;").replace(/  /g,"&nbsp;").replace(/<|>/g,"&gt;").replace(/\n/g,"<br />");var i=c.html();if(n+"&nbsp;"!=i){c.html(n+"&nbsp;");if(Math.abs(c.height()+h-g.height())>3){var m=c.height()+h;if(m>=j){l(j,"auto")}else{if(m<=k){l(k,"hidden")}else{l(m,"hidden")}}}}}g.css({overflow:"hidden"});g.keyup(function(){e()});g.live("input paste",function(i){setTimeout(e,250)});e()})}})})(jQuery);;
