/*	When document is full loaded (ready) init
 *  dom element's behaviours and animations 
 */

function mycarousel_getItemHTML(item)
{
    return '<img src="' + item.url + '" width="70" height="47" alt="' + item.title + '" />';
};
function mycarousel_itemVisibleInCallback(carousel, item, i, state, evt)
{
    // The index() method calculates the index from a
    // given index who is out of the actual item range.
    var idx = carousel.index(i, mycarousel_itemList.length);
    carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[idx - 1]));
};

function mycarousel_itemVisibleOutCallback(carousel, item, i, state, evt)
{
    carousel.remove(i);
};

$.fn.hasAttr = function(name) {  
   return this.attr(name) !== undefined;
};

/**
 * Item html creation helper.
 */


function changeStorageSelection(el, newact, form)
{
    oldact = $('#'+form).attr('action');
    $('#'+form).attr('action',newact);
    $(el).unbind();
    $(el).attr('onclick','changeStorageSelection(this,"'+oldact+'","'+form+'")');
    $(el).bind('click',function(){
       changeStorageSelection(el,oldact,form);
    })
    if ($(el).hasClass('checkNow')) {
        $(el).html($uncheckAll);
        $(el).addClass('uncheckNow'); 
        $(el).removeClass('checkNow');
        $(el).parent('div').parent('fieldset').children('table').children('tbody').children('tr').children('td.check').children('input').attr('checked',true); 
        //[name="offer_2"][type="checkbox"]
		//alert('check'); 
         
    } else if ($(el).hasClass('uncheckNow')) {
        $(el).html($checkAll); 
        $(el).removeClass('uncheckNow');
        $(el).addClass('checkNow');
        $(el).parent('div').parent('fieldset').children('table').children('tbody').children('tr').children('td.check').children('input').attr('checked',false); 
    }
}

function submitComparisonForm(id, url)
{
    oldact = $('#'+id).attr('action');
    
    $('#'+id).attr('method', 'GET');
    $('#'+id).attr('action', url);
    newDialog = window.open('about:blank', '_form');
    $('#'+id).attr('target', '_form');
    $('#'+id).submit();
    
    $('#'+id).removeAttr('target');
    $('#'+id).attr('method', 'POST');
    $('#'+id).attr('action', oldact);
}
/**
 * simple search action - field focus action
 * when field is clicked original text disappears
 */
function searchFocus(event) {
	var it = event.currentTarget;
	var orginal = $(it).prev('input').val();
	var newtext = $(it).val();
	if(orginal == newtext) $(it).val('');
}

/**
 * simple search action - field blur action
 * when field have no value original text apears
 */
function searchBlur(event) {
	var it = event.currentTarget;
	var orginal = $(it).prev('input').val();
	var newtext = $(it).val();
	if(newtext == '') $(it).val(orginal);
} 

/**
* simple search action - submit form
* when fields 'whare' and 'what' wasn't clicked it will set them value null
*/
function whatWhereSubmit(event) {
	if ($('#searchWhat').val() == $('#searchWhat').prev('input').val()){
		//$('#searchWhat').attr('disabled','true');
		$('#searchWhat').val('');
	} else {
		var what = $('#searchWhat').val();
		what = what.toLowerCase();
		 $('#searchWhat').val(what);
	}
	 if ($('#searchWhere').val() == $('#searchWhere').prev('input').val()){
		//$('#searchWhere').attr('disabled','true');
		$('#searchWhere').val('');
	} else {
	var where = $('#searchWhere').val();
			where = where.toLowerCase();
			$('#searchWhere').val(where);
	}
} 

jQuery(document).ready(function() {
    
    $("#offer_industry_idId.other").change(function(){
        if ($("#offer_industry_idId").val() == $bookCategoryId) {
            window.location.href = server_url + 'dodaj-podrecznik';
        } else if ($("#offer_industry_idId").val() == $estateCategoryId) {
            window.location.href = server_url + 'dodaj-nieruchomosc';
        } 
    });
    
    $("select#offer_industry_idId.book").change(function(){
        if ($("#offer_industry_idId").val() == $estateCategoryId) {
            window.location.href = server_url + 'dodaj-nieruchomosc';
        } else if ($("#offer_industry_idId").val() != $bookCategoryId) {
            window.location.href = server_url + 'dodaj-oferte/' + $("#offer_industry_idId").val();
        } 
    });
    
    $("select##offer_industry_idId.estate").change(function(){
        if ($("#offer_industry_idId").val() == $bookCategoryId) {
            window.location.href = server_url + 'dodaj-podrecznik';
        } else if ($("#offer_industry_idId").val() != $estateCategoryId) {
            window.location.href = server_url + 'dodaj-oferte/' + $("#offer_industry_idId").val();
        } 
    });
    
    //offer city autocompleter
    $("#offer_cityId").autocomplete(
        server_url+"/pobierz_miasto/", {
            matchContains: true,
            minChars: 0,
            autoFill: true,
            extraParams: {
                state_id: function() { return $("#offer_state_idId").val()}
            }
        }
    ).result(function(event, data, formatted) {
        if (data) {
            $("input#offer_city_idId").val(data[1]);

            var city = $('#offer_cityId').val();
        } else {
            $("input#offer_city_idId").val(0);
        }
    });

    //estate type
    $("#estate_type").autocomplete(
        server_url+"/pobierz_typ_nieruchomosci/", {
            matchContains: true,
            minChars: 0,
            autoFill: true,
            extraParams: {
                state_id: function() { return $("#offer_state_idId").val()}
            }
        }
    ).result(function(event, data, formatted) {
        if (data) {
            $("input#offer_city_idId").val(data[1]);

            var city = $('#offer_cityId').val();
        } else {
            $("input#offer_city_idId").val(0);
        }
    });
    
    //estate type
    $("div.estate input#offer_titleId").autocomplete(
        server_url+"/pobierz_typ_nieruchomosci/", {
            matchContains: true,
            minChars: 0,
            autoFill: true
        }
    ).result(function(event, data, formatted) {
            var sub = window.location.hostname.split(".");
            var subdomain;
            var state_id_subdomain = null;
            if(sub.length > 1) {
                if (sub[1] != 'pl') {
                    subdomain = sub[0];
                    $.getJSON(server_url+'get_state_id_for_subdomain/'+subdomain+'/', function(data2){
                        state_id_subdomain = parseInt(data2);
                    })
                }
            }

            $.getJSON(server_url+'get_states_for_estate/'+$('#offer_titleId').val()+'/', function(data){ //
                $('#offer_state_idId').empty();
                var notResp = 0;
                $.each(data, function(i,item){
                    if (state_id_subdomain != null) {
                        if (i == state_id_subdomain) {
                            $('#offer_state_idId').append('<option value="'+i+'" selected="selected">'+item+'</option>');
                        }else{
                            $('#offer_state_idId').append('<option value="'+i+'" disabled="disabled">'+item+'</option>');
                        }
                    } else {
                        $('#offer_state_idId').append('<option value="'+i+'">'+item+'</option>');
                    }
                    notResp ++;
                });
                if(notResp > 1) {
                    $('#offer_state_idId').removeAttr('disabled');
                } else {
                    $('#offer_state_idId').attr('disabled', 'disabled');
                }
            })
    

//        if (data) {
//            $("input#offer_city_idId").val(data[1]);
//
//            var city = $('#offer_cityId').val();
//        } else {
//            $("input#offer_city_idId").val(0);
//        }
    });

    //book city
    $("#book_cityId").autocomplete(
        server_url+"/pobierz_miasto/", {
            matchContains: true,
            minChars: 0,
            autoFill: true,
            extraParams: {
                state_id: function() { return $("#book_state_idId").val()}
            }
        }
    ).result(function(event, data, formatted) {
        if (data) {
            $("input#book_city_idId").val(data[1]);

            var city = $('#book_cityId').val();
        } else {
            $("input#book_city_idId").val(0);
        }
    });
    
 	if ($('#searchWhat').length > 0) {
		$('#searchWhat').focus(searchFocus);
		$('#searchWhat').blur(searchBlur);
	} 
 	if ($('#whatWhere').length > 0) {
		$('#whatWhere').submit(whatWhereSubmit);
	} 
    $('input.datePicker').datepicker();
	
/* adOcean START */
    $('#adhtml_obszary > div').each(function(){
        var place = $(this).attr('id').replace(/adhtml/gi,'adholder');
        if($('#'+place).length > 0 && $(this).find(':not(script)').length > 0){
            $(this).find('script').remove();
            $('#'+place).append($(this).children());
        }
    }).filter(':empty').remove();
    $('#adhtml_obszary > div:empty').remove();
/* adOcean END */

/**
 * Wyswietlanie ukrytych podpowiedzi
 */	
	$('div.infoIco').hover(function(){
		
		var off = $(this).offset();
		var description = $(this).children('span.hiddenInfo').html();
		var divInfoHidden = '<div class="mainInfoHidden2" style="z-index:5;"></div>';
		var spanInside = $("<span></span>").html(description);
		var defaultHeight='auto';
		$('body').append(divInfoHidden);
		$('div.mainInfoHidden2').append(spanInside);
		
		if (description.length<70){defaultHeight='60px'}
				
		
		$('div.mainInfoHidden2').attr({
			"style": "top:" + (off.top) + "px;left:" + (off.left+35) + "px; position:absolute; display:block; 	width:150px; height:"+defaultHeight+";"
	});

		
	},function(){
		$('div.mainInfoHidden2').css('display','none');
		$('div.mainInfoHidden2').children('span').html('');
		$('div.mainInfoHidden2').remove();
	});	
		

	$('.tabOfferDetail').click(function(){
		if($(this).hasClass('photoTab')){
			
			$('#offerTabs').children('li').each(function(){
				
				$(this).attr('class','noactive');
			});
			$(this).parent('li').removeClass('noactive').addClass('active');
			$('#offerDetailTabVideoContainer').addClass('hidden');
            $('#offerDetailTabVideoContainer').removeClass('show');
			$('#offerDetailTabPhotoContainer').fadeIn();
		}
		else{
			$('#offerTabs').children('li').each(function(){
				
				$(this).attr('class','noactive');
			});
			$(this).parent('li').removeClass('noactive').addClass('active');
			$('#offerDetailTabVideoContainer').removeClass('hidden');
            $('#offerDetailTabVideoContainer').addClass('show');
            $('#offerDetailTabPhotoContainer').hide();
			
		}
	})

/**
 * jSlide - main Site Script
 */
    
	/*
	$('#slideshow').hover(
	    function() { $('#controls').fadeIn(); },
	    function() { $('#controls').fadeOut(); }
	);
	*/	
	
	if ($("a[rel='lightbox']").length > 0) {
        $("a[rel='lightbox']").lightBox();
    }
    
/**
 * jCarousel Script
 */
	
	$('#mycarousel').empty();

    if (jQuery('#jCarouselPhotoCount')[0]) {
        jQuery('#mycarousel').jcarousel({
                    scroll: 1,
                    size: jQuery('#jCarouselPhotoCount')[0].value,
            itemVisibleInCallback: {onBeforeAnimation: mycarousel_itemVisibleInCallback},
            itemVisibleOutCallback: {onAfterAnimation: mycarousel_itemVisibleOutCallback}
        });
    }

}); //end of ready function for mycarousel

function jcarouselClick() {
    var alt = $(this).find('img').attr('alt');
    $('#mainOfferPhoto img').removeClass('big');
    $('#mainOfferPhoto img').each(function(){
        if($(this).attr('alt') == alt){
            $(this).addClass('big');
            return;
        }
    })
}

function unactivateUploadBox(name) {
    $('#'+name).find('div').each(function(){
        if ($(this).attr('id'))
            $(this).attr('id', $(this).attr('id')+'temp');
    });
    $('#'+name).find('span').each(function(){
        if ($(this).attr('id'))
            $(this).attr('id', $(this).attr('id')+'temp');
    });
    $('#'+name).find('form').each(function(){
        if ($(this).attr('id'))
            $(this).attr('id', $(this).attr('id')+'temp');
    });
    $('#'+name).find('input').each(function(){
        if ($(this).attr('id'))
            $(this).attr('id', $(this).attr('id')+'temp');
    });
    $('#'+name).find('a').each(function(){
        if ($(this).attr('id'))
            $(this).attr('id', $(this).attr('id')+'temp');
    });
}

function activateUploadBox(name) {
    $('#'+name).find('div').each(function(){
        if ($(this).attr('id'))
            $(this).attr('id', $(this).attr('id').replace("temp", ""));
    });
    $('#'+name).find('span').each(function(){
        if ($(this).attr('id'))
            $(this).attr('id', $(this).attr('id').replace("temp", ""));
    });
    $('#'+name).find('form').each(function(){
        if ($(this).attr('id'))
            $(this).attr('id', $(this).attr('id').replace("temp", ""));
    });
    $('#'+name).find('input').each(function(){
        if ($(this).attr('id'))
            $(this).attr('id', $(this).attr('id').replace("temp", ""));
    });
    $('#'+name).find('a').each(function(){
        if ($(this).attr('id'))
            $(this).attr('id', $(this).attr('id').replace("temp", ""));
    });
}



/*********************
 * GLOBAL FUNCTIONS *
 *********************/
var _w = window; // window alias
var _d = document; // document alias

/**
 * alias document.getElementById()
 * id - element id
 */
function _id(id){return _d.getElementById(id)}

/**
 * Steps settings
 */


step=2;
var stepStart=2;

/**
 * Go to next step
 */
function nextStep() {
	
	$('div.errorFormValidation').css('display','none');
	var errors = 0;
	var steps = $('.offerStep').length;
	var v = $("#editEstateFormPart2").validate({
	    ignore: ".ignore",
	    errorElement: "span",
	    errorClass: "messageError",
	
		invalidHandler: function(form, validator) {	
	    errors = validator.numberOfInvalids();
		    if (errors) {
			  	
				if ($('.multiCheckField').length > 0) {
					multiChCountError = $('div.errorFormValidation b.multiChCount').html();
					//alert("multiChCountError="+multiChCountError+', '+errors);
					
					errors = parseInt(errors);
					multiChCountError = parseInt(multiChCountError);
					if (multiChCountError) {
						errors = errors + multiChCountError;
					}
				}
				
				$('div.errorFormValidation').html('Formularz zawiera błędy, ilośc błędów  (<b>'+errors+'</b>)');
				$('div.errorFormValidation').css('display','block');
		
		    } else {
			  	$('div.errorFormValidation').html('');
			  	$('div.errorFormValidation').css('display','none');
		    }
		 }
	});
	
	function multiCheck_Check(){
		
	var multiFalse=0;
			if (!isCheckedByName("multiCheckDestination"))
			{multiFalse=multiFalse+1;}				
						
			if (!isCheckedByName("multiCheckEntries"))
			{multiFalse=multiFalse+1;}
							
			if (!isCheckedByName("multiCheckFields"))
			{multiFalse=multiFalse+1;}	
			
			return multiFalse;	
	};
		
	function isCheckedByName(check_name)
	{
		var checked = $("div."+check_name+" div.singleMultiCheck input:checked").length;
			
		if (checked == 0){
			$("div."+check_name+" span.specialChGroupError").css('display','block');
			return false; 	
		}
		else{
			$("div."+check_name+" span.specialChGroupError").css('display','none');
			return true;
		}				
	}
	
	var multiChOK='true';	
	if (step == 3) {
		
		if ($('.multiCheckField').length > 0) {
			var multiChCount = multiCheck_Check();
			if (!multiChCount) 
				multiChOK = true;
			else 
				multiChOK = false;
			
			if (!multiChOK) {
				$('div.errorFormValidation').html('Formularz zawiera błędy, ilośc błędów  (<b class="multiChCount">' + multiChCount + '</b>)');
				$('div.errorFormValidation').css('display', 'block');
			}
			else {
				$('div.errorFormValidation').html('');
				$('div.errorFormValidation').css('display', 'none');
			}
		// alert(multiChCount);
		}
	}
	
    if (step<=steps) {
        $('.offerStep input').addClass('ignore');
        $('.offerStep select').addClass('ignore');
        $('#step' + step + ' input').removeClass('ignore');   
        $('#step' + step + ' select').removeClass('ignore');
        if(!v.form()) {return false;}

		if (multiChOK) {
			step++;
			
			$('#prevStep').removeClass('none');
			$('#firstStep').addClass('none');
			$('.offerStep').addClass('none');
			$('#step' + step).removeClass('none');
			$("a[href='#step" + (step) + "']").addClass('active');
			
			if ($('#step' + step).hasClass('offerStepLast')) {
				$(this).addClass('none');
				$(this).attr('disabled', 'disabled');
				$('#saveOffer').removeClass('none');
				$('#saveOffer').removeAttr('disabled');
			}
			
		}
    }
}


/**
 * Go to previous step
 */
function prevStep() {
    if (step != stepStart) {
        step--;
        $('.offerStep').addClass('none');
        $('#step' + step).removeClass('none');
        $("a[href='#step" + (step+1) + "']").removeClass('active');
        
        $('.offerStep input').addClass('ignore');
        $('.offerStep select').addClass('ignore');
        $('#step' + step + ' input').removeClass('ignore');   
        $('#step' + step + ' select').removeClass('ignore');
        
        if(!$('#step' + step).hasClass('offerStepLast')){
            $('#nextStep').removeClass('none');
            $('#nextStep').removeAttr('disabled');
            $('#saveOffer').addClass('none');
            $('#saveOffer').attr('disabled','disabled');
        }
        if(step==stepStart){
            $('#firstStep').removeClass('none');
            $(this).addClass('none');
            //$(this).attr('disabled','disabled');
        }
    }
}

function saveOffer() {
    var v = $("#editEstateFormPart2").validate({
        ignore: ".ignore",
        errorElement: "span",
        errorClass: "messageError"
    });
    $('.offerStep input').addClass('ignore');
    $('.offerStep select').addClass('ignore');
    $('#step' + step + ' input').removeClass('ignore');   
    $('#step' + step + ' select').removeClass('ignore');
   if(v.form()) {return true} else {return false}
}

function disableEnterKey(event) {
    if (event.keyCode == 13) {return false}
}

function ajax(url,question) {
    $.ajax({
        type: 'POST',
        url: 'index.php?module=regioMotoOffers&evt=ajaxGetTransactionType',
        dataType: 'json',
        data: {category_id:value},
        success: function(data) {
           alert(data)
        }            
    });
}
function setOther(num) {
    if (hiddenOtherVehicleType!='' && num == 1) {
        hiddenOtherVehicleType=parseInt(hiddenOtherVehicleType);
        $('select#other_vehicle_type_idId').val(hiddenOtherVehicleType);
        hiddenOtherVehicleType = '';
        getOtherType();
    }
    if (hiddenVehicleType!='' && num == 2) {
        hiddenVehicleType=parseInt(hiddenVehicleType);
        $('select#vehicle_type_idId').val(hiddenVehicleType);
        hiddenVehicleType = '';
    }
    
}


function showField(id) {
    if ($(_id(id)).parent('div').hasClass('none')) {
        $(_id(id)).parent('div').removeClass('none');
        $(_id(id)).removeAttr('disabled');
    }
}
function hideField(id) {
    if (!$(_id(id)).parent('div').hasClass('none')) {
        $(_id(id)).parent('div').addClass('none');
        $(_id(id)).attr('disabled', 'disabled');
    }
}

function set(len) {
    if (hiddenVehicleType!='' && len <= 5) {
        hiddenVehicleType=parseInt(hiddenVehicleType);
        $('select#vehicle_type_idId').val(hiddenVehicleType);
        hiddenVehicleType = '';
    }
    
    if (hiddenOtherVehicleType!='' && len <= 5) {
        hiddenOtherVehicleType=parseInt(hiddenOtherVehicleType);
        $('select#other_vehicle_type_idId').val(hiddenOtherVehicleType);
        hiddenOtherVehicleType = '';
    }
    
    if (hiddenTransactionType!='' && len <= 5) {
        hiddenTransactionType=parseInt(hiddenTransactionType);
        $('select#transaction_type_idId').val(hiddenTransactionType);
        hiddenTransactionType = '';
    }
    
    if (hiddenBrandId!='' && len <= 4) {
        hiddenBrandId=parseInt(hiddenBrandId);
        $('select#brand_idId').val(hiddenBrandId);
        hiddenBrandId = '';
    }
    
    if (hiddenModelId!='' && len == 3) {
        hiddenModelId=parseInt(hiddenModelId);
        $('select#model_idId').val(hiddenModelId);
        hiddenModelId = '';
    }
}
function disableBigBox(target) {
    var div = $('<div></div>');
    var t = $(_id(target));
    
    var w = t.outerWidth();
    var h = t.outerHeight();
    var off = t.offset();
    
    div.css({
        'left': off.left,
        'top': off.top,
        'width':w,
        'height':h,
        'opacity':0.2,
        'background-color':'#000',
        'position':'absolute'
    });
    $('body').after(div);
}

getTransactionTypeOffer = function(){
    $.ajax({
        type: 'POST',
        url: 'index.php?module=offers&evt=ajaxGetTransactionType',
        dataType: 'json',
        data: {category_id:$('#category_idId').val()},
        beforeSend: insertAjaxLoader('transaction_type_idId','s'),
        success: function(data){
            $('#transaction_type_idId').empty();
            if (data.options.length) {
                for (i = 0; i < data.options.length; i++) {
                    $('#transaction_type_idId').append(data.options[i]);
                }
                if (transaction_type_selected != undefined) {
                    $('#transaction_type_idId').val(transaction_type_selected);
                    transaction_type_selected = false;
                }
				
				if (hiddenTransactionType!='') {
					hiddenTransactionType=parseInt(hiddenTransactionType);
					$('select#transaction_type_idId').val(hiddenTransactionType);
				}

            }
            removeAjaxLoader('transaction_type_idId')
        }
    });
}
getModelOffer = function(){
    if ($('#brand_idId').val() == 0 || $('#brand_idId').val() == undefined) {return false};
    if ($('#category_idId').val() == 5) {
        vehicle_type = 'all_car';
    }else{
        vehicle_type = $('#vehicle_type_idId').val();
    }
    
    
    var question = {brand_id:$('#brand_idId').val(), type_id:vehicle_type};
    $.ajax({
        type: 'GET',
        url: 'index.php?module=offers&evt=ajaxGetModelForBrand',
        dataType: 'json',
        data: question,
        beforeSend: function(){
            insertAjaxLoader('model_idId','s');
            insertAjaxLoader('model_nameId','s');
        },
        success: function(data) {
            removeAjaxLoader('model_idId');
            removeAjaxLoader('model_nameId');
            $('#model_idId').empty().removeAttr('disabled');
            if (data != false) { // gdy wybierzesz nowe,uzywane,moto,inne
                $('#model_idId').removeAttr('disabled').parent('div').removeClass('none');
                $('#model_nameId').attr('disabled','disabled').parent('div').addClass('none');

				 for (i in data) {
					var opt = $('<option value="'+i+'"></option>');
                    $('#model_idId').append($(opt).append(data[i]));
                }
            } else { // gdy wybierzesz czesci
                $('#model_nameId').removeAttr('disabled').parent('div').removeClass('none');
                $('#model_idId').attr('disabled','disabled').parent('div').addClass('none');
            }
            
			set(3)
            if (model_selected) {
                $('#model_idId').val(model_selected);
                model_selected = false;
            }
			
			/*
			if (model_idId!='') {
				model_idId=parseInt(model_idId);
				$('select#model_idId').val(model_idId);
			}	
			*/		
			
        }            
    }); 
}
getBrandOffer = function() {
    if ($('#vehicle_type_idId').val() == 0 || $('#vehicle_type_idId').val() == undefined)  {return false};
    if ($('#category_idId').val() == 5) {
        var question = {vehicle_type_id:'all_car'};
    }else{
        var question = {vehicle_type_id:$('#vehicle_type_idId').val()};
    }
    $.ajax({
        type: 'POST',
        url: 'index.php?module=offers&evt=ajaxGetBrandVehicle',
        dataType: 'json',
        data: question,
        beforeSend: insertAjaxLoader('brand_idId','s'),
        success: function(data) {
            $('#brand_idId').empty().append('<option>--</option>').attr('disabled','disabled');
            $('#model_idId').empty().attr('disabled','disabled');
            $('#model_nameId').empty().attr('disabled','disabled');
			$('#brand_idId').empty();
            for (i = 0; i < data.options.length; i++){
                $('#brand_idId').append(data.options[i]);
            }
            if (brand_selected) {
                $('#brand_idId').val(brand_selected).change();
                brand_selected = false;
            }
            set(4);
            getModelOffer()
            removeAjaxLoader('brand_idId')
			/*
			if (hiddenBrandId!='') {
				hiddenBrandId=parseInt(hiddenBrandId);
				$('select#brand_idId').val(hiddenBrandId);
				$('select#brand_idId').attr('disabled','');
			}	*/		
        },
        	error : function(){
            $('#brand_idId').empty().append('<option>--</option>').attr('disabled','disabled');
            $('#model_idId').empty().attr('disabled','disabled');
            $('#model_nameId').empty().attr('disabled','disabled');
            removeAjaxLoader('brand_idId');
        }          
    });
}
getOtherType = function(){
	
    setOther(1);
    var question = {
        type_id:$('#other_vehicle_type_idId').val()
    };
    $('#vehicle_type_idId').empty()
    $.ajax({
        type: 'POST',
        url: 'index.php?module=offers&evt=ajaxGetOtherVihickleType',
        dataType: 'json',
        data:question,
        beforeSend: function(){
            showField('vehicle_type_idId');
            insertAjaxLoader('vehicle_type_idId', 's')
        },
        success: function(data) {
            removeAjaxLoader('vehicle_type_idId');
            $('#brand_idId').empty().append('<option>--</option>').attr('disabled','disabled');
            $('#model_idId').empty().attr('disabled','disabled');
            if(data == null){
                hideField('vehicle_type_idId');
                return false;
            }
            if (data.options.length) {
                $('#other_vehicle_type_idId').change(getOtherType);
                for (i = 0; i < data.options.length; i++) {
                    $('#vehicle_type_idId').append(data.options[i]);
                }
                setOther(2);
            }
			
        }
    }); 
}
getPartType = function(){
    var question = {category_id:$('#category_idId').val(), element_category_id: $('#vehicle_type_idId').val()};
    if ($('#vehicle_type_idId').val() == 0) {
        question['element_category_id'] = vehicle_type_selected;
        question['parent'] = 1;
    }
    $.ajax({
        type: 'POST',
        url: 'index.php?module=offers&evt=ajaxGetVihickleType',
        dataType: 'json',
        data: question,
        beforeSend: insertAjaxLoader('vehicle_type_idId','s'),
        success: function(data) {
            if (data.options.length) {
               // $('#vehicle_type_idId').find('option').attr('disabled','disabled');
               $('#vehicle_type_idId').empty()
                for (i = 0; i < data.options.length; i++) {
                    $('#vehicle_type_idId').append(data.options[i]);
                }
                vehicle_type_selected = data.id;
            }
            $('#brand_idId').empty().append('<option>--</option>').attr('disabled','disabled');
            $('#model_nameId').empty().attr('disabled','disabled');
            getBrandOffer()
            removeAjaxLoader('vehicle_type_idId')
        }            
    });
}

function showField(id) {
    if ($(_id(id)).parent('div').hasClass('none')) {
        $(_id(id)).parent('div').removeClass('none');
        $(_id(id)).removeAttr('disabled');
    }
	
	if (id == 'capacityId') {
		$('#capacityId').removeAttr('disabled');
	}
}
function hideField(id) {
    if (!$(_id(id)).parent('div').hasClass('none')) {
        $(_id(id)).parent('div').addClass('none');
        $(_id(id)).attr('disabled','disabled');
    }
	
	if (id == 'capacityId') {
		$('#capacityId').attr('disabled', 'disabled');
	}
}
addOffer = function(){
    $('#vehicle_type_idId').empty();
    getTransactionTypeOffer();
    $('.messageError').hide()
    
};
addOffer.prototype.normals = function(){
    var question = {category_id:$('#category_idId').val()};
    $('input#evt').val('addOfferPart2');
    
    //showField('capacityId');  //capacity 2010.03.03 zmiana
    hideField('model_idId');
    showField('model_nameId');
    $('#model_nameId').attr('disabled','disabled')
    hideField('other_vehicle_type_idId');
    hideField('price_negotiation');
    showField('brand_idId');
    showField('vehicle_type_idId');
    if ($('#idId').val()) {
        question['only'] = $('#vehicle_type_idId').val();
    }
    $.ajax({
        type: 'POST',
        url: 'index.php?module=offers&evt=ajaxGetVihickleType&no_all=on',
        dataType: 'json',
        data: question,
        beforeSend: insertAjaxLoader('vehicle_type_idId','s'),
        success: function(data) {
            $('#brand_idId').empty().append('<option>--</option>').attr('disabled','disabled');
            $('#model_idId').empty().attr('disabled','disabled');
            for (i = 0; i < data.options.length; i++){
                $('#vehicle_type_idId').append(data.options[i]);
            }
            if (selected_type) {
                $('#vehicle_type_idId').val(selected_type).change();
                selected_type = false;
            }
            set(5);
            getBrandOffer();
            $('#vehicle_type_idId').unbind().bind('change',getBrandOffer);
			$('#brand_idId').empty();
            $('#brand_idId').change(getModelOffer);
            removeAjaxLoader('vehicle_type_idId');
         
			$('.hiddenPostLink').val('addOfferPart2');  
		    if(_id('vehicle_type_id_hidden')){
                disableBigBox('vehicle_type_idId');
                disableBigBox('other_vehicle_type_idId');
            }
			/*if (hiddenVehicleType!='') {
				hiddenVehicleType=parseInt(hiddenVehicleType);
				$('select#vehicle_type_idId').val(hiddenVehicleType);
			}*/
        }
    });
}
addOffer.prototype.others = function(){
    $('input#evt').val('addOtherOfferPart2');
    var question = {type_id:$('#category_idId').val()};
    
    $('#other_vehicle_type_idId').empty();
    hideField('capacityId');
	//$('#capacityId').attr('disabled','disabled');
    hideField('model_idId');
    showField('model_nameId');
    $('#model_nameId').removeAttr('disabled')
    showField('other_vehicle_type_idId');
    showField('price_negotiation');
    hideField('brand_idId');
    hideField('model_idId');
    hideField('vehicle_type_idId');
    
    $.ajax({
        type: 'POST',
        url: 'index.php?module=offers&evt=ajaxGetOtherCategories',
        dataType: 'json',
        beforeSend: insertAjaxLoader('other_vehicle_type_idId','s'),
        success: function(data) {
            $('#brand_idId').empty().append('<option>--</option>').attr('disabled','disabled');
            $('#model_idId').empty().attr('disabled','disabled');
            
            if (data.options.length) {
                for (i = 0; i < data.options.length; i++) {
                    $('#other_vehicle_type_idId').append(data.options[i]);
                }
            }
            setOther(1);
            $('#other_vehicle_type_idId').bind('change',getOtherType);
            $('#vehicle_type_idId').unbind();
            removeAjaxLoader('other_vehicle_type_idId');
            if (vehicle_type_selected) {
                $('#other_vehicle_type_idId').val(vehicle_type_selected);
                vehicle_type_selected = false;
            }
         
			$('.hiddenPostLink').val('addOtherOfferPart2'); 
			/*
			if (hiddenOtherVehicleType!='') {
				hiddenOtherVehicleType=parseInt(hiddenOtherVehicleType);
				$('select#other_vehicle_type_idId').val(hiddenOtherVehicleType);
			} */
        }
    }); 
}

addOffer.prototype.parts = function(){
    
    $('input#evt').val('addPartOfferPart2');
    if (hiddenVehicleType != '') {
        hiddenVehicleType = parseInt(hiddenVehicleType);
        var question = {category_id: $('#category_idId').val(),element_category_id: hiddenVehicleType, element_last: 1};
    }
    else {
        var question = {category_id: $('#category_idId').val(),element_category_id: 2};
    }
    
    hideField('capacityId');
    hideField('model_nameId');
    hideField('other_vehicle_type_idId');
    showField('price_negotiation');
    showField('vehicle_type_idId');
    showField('brand_idId');
    $('#brand_idId').attr('disabled','disabled');
    showField('model_nameId');
    $('#model_nameId').removeAttr('disabled');
    
    if ($('#category_idId').val() == 0) {
        question['element_category_id'] = vehicle_type_selected;
        question['parent'] = 1;
    }
    
    $.ajax({
        type: 'POST',
        url: 'index.php?module=offers&evt=ajaxGetVihickleType',
        dataType: 'json',
        data: question,
        beforeSend: insertAjaxLoader('vehicle_type_idId','s'),
        success: function(data) {
            
            if (data.options.length) {
                for (i = 0; i < data.options.length; i++) {
                    $('#vehicle_type_idId').append(data.options[i]);
                }
                vehicle_type_selected = data.id;
            }
            if (hiddenVehicleType != '') {
                $('select#vehicle_type_idId').val(hiddenVehicleType);
                hiddenVehicleType = '';
                getPartType();
            }
            removeAjaxLoader('vehicle_type_idId');
            $('#vehicle_type_idId').unbind().bind('change',getPartType)
        }            
    });  
}

function changeCategory(event) {
    if(event.currentTarget){
        var it = $(event.currentTarget).val();
		$('#model_nameId').val('');
    }else{
        var it = $(_id(event)).val();
    }
    offer = new addOffer;
	
    if(it == '1' || it == '2' || it == '3'){
        transaction_type_selected = $('#transaction_type_idId').val();
        brand_selected = $('#brand_idId').val();
        model_selected = $('#model_idId').val();
        selected_type = $('#vehicle_type_idId').val();
        
        offer.normals();
        //AaddOfferGetTypes($(event.currentTarget))
    }else if (it == '6') {
        var vehicle_type_selected = false;
        
        offer.others();
        //AaddOtherGetVehicleType()
    }else if (it == '5'){
        var vehicle_type_selected = $('#vehicle_type_idId').val();
        var model_selected = $('#model_idId').val();

        offer.parts();
        //AaddPartGetVehicleType(event.currentTarget)
    }

}

var brand_selected = false;
var model_selected = false;
var selected_type = false;
var transaction_type_selected = false;


/**
 * inserts ajax loader image to specified target 
 * target - id of element where loader will be appended
 */
function insertAjaxLoader(target) {
	
	/* remove ajax loader 
	if(typeof target == 'string'){
        $(_id(target)).removeAttr('disabled');
    }else {
        $(target).removeAttr('disabled');
    }
    */
    $(_id('ajaxLoader')).css('display','none');//remove();
	
    var div = $('<div></div>');
    
    if(typeof target == 'string'){
        var t = $(_id(target));
    }else {
        var t = $(target);
    }
    
    var w = t.outerWidth();
    var h = t.outerHeight();
    var off = t.offset();
    
    div.attr('id','ajaxLoader');
    div.css({
        'left': off.left,
        'top': off.top,
        'width':w,
        'height':h,
        'opacity':0.5
    });

    if (arguments[1] != undefined && arguments[1] != 's') {
        $(_id(target)).attr({
            'disabled': 'disabled'
        })
    }
    $('body').append(div);
}

/**
 * removes ajax loader image from specified target
 * target - id of element where loader was appended
 */
function removeAjaxLoader(target) {
    if(typeof target == 'string'){
        $(_id(target)).removeAttr('disabled');
    }else {
        $(target).removeAttr('disabled');
    }
    $(_id('ajaxLoader')).remove();
}




$(document).ready(function(){
	

	$(".datepicker, .datePicker").datepicker({
		showOn: 'button',
		buttonImage: server_url+'public/images/ico_calendar.gif',
		buttonImageOnly: true,
		dateFormat: 'yy-mm-dd'
	});
	
	
	$(".datepickerYearMonth").datepicker({
		showOn: 'button',
		buttonImage: server_url+'public/images/ico_calendar.gif',
		buttonImageOnly: true,
		dateFormat: 'yy-mm'
	});
		
	


if($('.calculatorMultiSelectContainer').length >0)
	$('.calculatorMultiSelectContainer').jScrollPane();
	
hiddenStepError=$('input.hiddenStepError').val();
if (hiddenStepError != '') step = hiddenStepError;

$('#category_idId, #transaction_type_idId').change(
 	function (){
		jsDynamicSearchFieldCheck();
	}
 );
 
function SD_Switch(fieldType){ //single to double switch
	var myFieldSingle="."+fieldType+'Single';
	var myFieldDouble="."+fieldType+'Double';
	
	
	$(myFieldSingle).hide();
	$(myFieldSingle+' input').addClass('ignore');
	$(myFieldSingle+' input').attr('disabled','disabled');
	
	$(myFieldDouble).show();
	$(myFieldDouble+' input').removeClass('ignore');
	$(myFieldDouble+' input').removeAttr('disabled');
}
 
function DS_Switch(fieldType){ //double to single switch
	var myFieldSingle="."+fieldType+'Single';
	var myFieldDouble="."+fieldType+'Double';
	
	$(myFieldSingle).show();
	$(myFieldSingle+' input').removeClass('ignore');
	$(myFieldSingle+' input').removeAttr('disabled');
	
	$(myFieldDouble).hide();
	$(myFieldDouble+' input').addClass('ignore');
	$(myFieldDouble+' input').attr('disabled','disabled');
}

function dsp_none(fieldType){
	var myField="."+fieldType;
	$(myField).hide();
	$(myField+' input').attr('disabled','disabled');
	$(myField+' input').addClass('ignore');
}

//jsDynamicSearchFieldCheck();
 
function jsDynamicSearchFieldCheck(){
	categoryType = $('#category_idId').val();
	transType = $('#transaction_type_idId').val();
	
	//alert(categoryType+' '+transType);

		if ((categoryType == 1 && transType == 2) ||
		(categoryType == 2 && transType == 2) ||
		(categoryType == 3 && transType == 2)) { //kupno, mieskzania - domy
			SD_Switch('year');
			SD_Switch('capacity');
			SD_Switch('price');
		}
		else if (categoryType == 5 || categoryType == 6){
			dsp_none('capacitySingle');
			dsp_none('capacityDouble');
			DS_Switch('year');
			DS_Switch('price');			
		}
		else {
			DS_Switch('year');
			DS_Switch('price');
			DS_Switch('capacity');
			/*
			if (categoryType == 5 || categoryType == 4){
			dsp_none('capacitySingle');
			}else DS_Switch('capacity');
			*/
	
		}

}	
		
	hiddenVehicleType=$('#hiddenVehicleType').val();		
	hiddenOtherVehicleType=$('#hiddenOtherVehicleType').val();	
	hiddenTransactionType=$('#hiddenTransactionType').val();
	hiddenBrandId=$('#hiddenBrandId').val();	
	hiddenModelId=$('#hiddenModelId').val();	
	
	
	//alert(hiddenVehicleType);
	//alert(hiddenTransactionType);
	
	$('#add_FirstStep #brand_idId').change(getModelOffer);
	
    //OFFERS/addOfferForm
    if (_id('addOfferForm')) {
        changeCategory('category_idId');
        $('#category_idId').change(changeCategory);
        //$('#vehicle_type_idId').change(addOfferGetBrand);
        //$('#brand_idId').change(getModel);
    }

	
	/*
		if (hiddenVehicleType!='') {
			hiddenVehicleType=parseInt(hiddenVehicleType);
			$('select#vehicle_type_idId').val(hiddenVehicleType);
		}
		
		if (hiddenOtherVehicleType!='') {
			hiddenOtherVehicleType=parseInt(hiddenOtherVehicleType);
			$('select#other_vehicle_type_idId').val(hiddenOtherVehicleType);
		}
		
		if (hiddenTransactionType!='') {
			hiddenTransactionType=parseInt(hiddenTransactionType);
			$('select#transaction_type_idId').val(hiddenTransactionType);
		}
		
		if (hiddenBrandId!='') {
			hiddenBrandId=parseInt(hiddenBrandId);
			$('select#brand_idId').val(hiddenBrandId);
		}
		
		if (hiddenModelId!='') {
			hiddenModelId=parseInt(hiddenModelId);
			$('select#model_idId').val(hiddenModelId);
		}
	*/

/* jCarousel functions */	
	$('.jcarousel-item').click(jcarouselClick)
    $('.jcarousel-next').click(function(){
        $('.jcarousel-item').click(jcarouselClick)
    })
    $('.jcarousel-prev').click(function(){
        $('.jcarousel-item').click(jcarouselClick)
    })
    
	$('.ubrFile').click(function(){
        if (typeof(currentForm) != "undefined") {
            uploadbox = $(this).parent('td').parent('tr').parent('tbody').parent('table').parent('div').parent('div').parent('form').parent('div').parent('div').parent('div');
            if (uploadbox.hasClass('videoUploadForm') && currentForm=='photos') {//switch to video
                max_upload_slots = 1;
                upload_range = 1;
                unactivateUploadBox('photosBox');
                activateUploadBox('videoBox');
                allow_extensions = videoExt;
                currentForm = 'video';
            } else if (!uploadbox.hasClass('videoUploadForm') && currentForm=='video') {//switch to photos
                max_upload_slots = 10;
                upload_range = 1;
                unactivateUploadBox('videoBox');
                activateUploadBox('photosBox');
                allow_extensions = photoExt;
                currentForm = 'photos';
            }
        }
    });
	
    $('.mainPhotoRadio').click(function(){
        document.location = $(this).val();
    });	

/* upload Video File - tab change */

$('.singleTab').click(function(){
	if ($(this).hasClass('videoFromDisk')) {
		$('div.videoUploadForm').css('display', 'block');
		$('div.videoLinkForm').css('display', 'none');
		$('div.videoYouTubeForm').css('display', 'none');
		$('.videoFromLink').removeClass('activeTab');
		$('.videoFromTube').removeClass('activeTab');
		$(this).addClass('activeTab');
	}
	if ($(this).hasClass('videoFromLink')) {
		$('div.videoUploadForm').css('display', 'none');
		$('div.videoYouTubeForm').css('display', 'none');
		$('div.videoLinkForm').css('display', 'block');
		$('.videoFromDisk').removeClass('activeTab');
		$('.videoFromTube').removeClass('activeTab');
		$(this).addClass('activeTab');
	}
	if ($(this).hasClass('videoFromTube')) {
		$('div.videoYouTubeForm').css('display', 'block');
		$('div.videoUploadForm').css('display', 'none');
		$('div.videoLinkForm').css('display', 'none');
		$('.videoFromDisk').removeClass('activeTab');
		$('.videoFromLink').removeClass('activeTab');
		$(this).addClass('activeTab');
	}
});
	

	
	//	rules: { 
	//	      sport: { 
	//	        selectNone: true 
	//	      } 
	//	    },

	hiddenStepError=$('input.hiddenStepError').val();
	if (hiddenStepError) step=hiddenStepError;
	
	//alert(step);
 
    
    // OFFERS/addEstateFormPart2
    if (_id('editEstateFormPart2')) {
        $('#nextStep').removeAttr('disabled');
        $('#editEstateFormPart2 #saveOffer').click(saveOffer);
		
      	$('#editEstateFormPart2 #nextStep') .click(nextStep);
      	$('#editEstateFormPart2 #prevStep') .click(prevStep);
        
        $('#editEstateFormPart2').keypress(disableEnterKey);

        $("#seller_cityId").autocomplete(server_url+"/pobierz_miasto/", {
	        matchContains: true,
	        minChars: 0,
	        autoFill: true,
	        extraParams: {
	    		state_id: function() { return $("#seller_state_idId").val()}
	    	}
	    }).result(function(event, data, formatted) {
    	if (data) {
            $("input#seller_city_idId").val(data[1]);

            var city = $('#seller_cityId').val();
            centerMap('Poland', city, '', '');
        } else {
            $("input#seller_city_idId").val(0);
        }
	    });
        
    }
	
	
	
/* jquery input to select */

/* violation_typeId - other violations */
	$('#violation_typeId').change(function(){
		if ($(this).attr('value')==3){
			$('.violation_others').css('display','block');//.slideDown();
		}
		else $('.violation_others').css('display','none');
	})


$("body").click(function(e){
  //you can then check what has been clicked
  var target = $(e.target); 
  var targetClass = target.attr('class');

	if (targetClass!='showInputSelect'){
		$('.inputSelect1').css('display','none');
		$('.inputToSelect').css('display','none');
	}
});


$('ul.inputSelect li').hover(function(){
	$(this).addClass('hover');
},function(){
	$(this).removeClass('hover');
});	

$('ul.inputSelect li').click(function(){
	
	ulDivClass=$(this).parent('ul').parent('.inputToSelect').attr('class');
	liExplode=ulDivClass.split(' ');
	searchID='#'+liExplode[1].substring(4);
	
	liOption=$(this).html();
	liOption=liOption.replace(/ /g,'');
	$(searchID).val(liOption);

})

$('body input.showInputSelect').click(function(){
	$('.inputToSelect').css('display','none');
	var off = $(this).offset();
	elFullID=$(this).attr('id')
	elID='div.its-'+elFullID;
	
	// alert(off.top+' '+off.left);
	
	$(elID).attr({
			"style": "top:" + (off.top+24) + "px;left:" + (off.left) + "px; position:absolute; display:block; z-index:11;"
		});
	
	$('.inputOnly').css('z-index', '1');
	$(this).parent('div').css('z-index', '10');
	
	/* deleting wrong values */

	inputEnd=elFullID.substr(elFullID.length-3,elFullID.length);
	inputEnd2=elFullID.substr(elFullID.length-2,elFullID.length);	

	if (inputEnd=='End' || inputEnd2=='To') {	
		
		if (inputEnd == 'End') {
			inputLength = elFullID.length - 3;
			inputFirstPart = elFullID.substr(0, inputLength);
			
			inputIDStart = "#" + inputFirstPart + "Start";
			
		}else if (inputEnd2 == 'To') {
			inputLength = elFullID.length - 2;
			inputFirstPart = elFullID.substr(0, inputLength);
			
			inputIDStart = "#" + inputFirstPart + "From";
					
		}

		prevInputValue=$(inputIDStart).attr('value');
		prevInputValue=prevInputValue.replace(/ /g,'');
		prevInputValue=parseFloat(prevInputValue);
		
		$(elID).children('ul').children('li').each(function(){
			thisValue=$(this).html();
			thisValue=thisValue.replace(/ /g,'');
			thisValue=parseFloat(thisValue);
			
			//alert(prevInputValue+' '+thisValue)
			
			if(thisValue<prevInputValue) $(this).css('display','none');
			else $(this).css('display','block');
		})
	} //if (inputEnd=='End' || inputEnd2=='To')


});

	var browserName=navigator.appName;
		/*
			if (browserName == 'Microsoft Internet Explorer') {
				//DO SOMETHING, example
				$(this).prev('table.hiddenRecords').css('display', 'block');
			}else{
				//DO SOMETHING ELSE, example
				$(this).prev('table.hiddenRecords').css('display', 'table');
			}
		*/
		
	$('div#mainSearch ul li').hover(function(){
		$(this).children('span.hiddenInfo').css('display','block');
	},function(){
		$(this).children('span.hiddenInfo').css('display','none');
	})
	
	$('div.changeRegion a.question').hover(function(){
		$(this).children('span.hiddenInfo').css('display','block');
	},function(){
		$(this).children('span.hiddenInfo').css('display','none');
	})

/*	
 * Zaznaczanie ofert w schowku - dziala - do zmiany kolejnosc elementow
 */
/*
	$('.checkAll').click(function(){
		if ($(this).hasClass('checkNow')) { 		
		// If you can checkAll
			$(this).html('Odznacz wszystkie');
			$(this).addClass('uncheckNow');
			$(this).removeClass('checkNow');
			
			$(this).parent('h2').next('div').next('table').children('tbody').children('tr').children('td.check').children('input').attr('checked', true);
		}
		else if ($(this).hasClass('uncheckNow')) { 
		// If you can UNcheckAll 
			$(this).html('Zaznacz wszystkie');
			$(this).removeClass('uncheckNow');
			$(this).addClass('checkNow');
			
			$(this).parent('h2').next('div').next('table').children('tbody').children('tr').children('td.check').children('input').attr('checked', false);
		}
	});
*/	
	$('a.showMoreRecordsLink').click(function(){
		if ($(this).hasClass('showAdditionalRecords')) {
		/* show additional records */

			//$(this).prev('span').parent('.numberOfRecordsShow').prev('div.hiddenRecords').css('display', 'block');
			$(this).parent('h2').next('div').next('table').next('div.hiddenRecords').css('display', 'block');
			$(this).html('ukryj dodatkowe');
			
			$(this).addClass('hideAdditionalRecords');
			$(this).removeClass('showAdditionalRecords');
		}
		else if ($(this).hasClass('hideAdditionalRecords')) {
		/* hide additional records */
			//$(this).prev('span').parent('.numberOfRecordsShow').prev('div.hiddenRecords').css('display', 'none');
			$(this).parent('h2').next('div').next('table').next('div.hiddenRecords').css('display', 'none');
			$(this).html('pokaż wszystkie');
			
			$(this).addClass('showAdditionalRecords');
			$(this).removeClass('hideAdditionalRecords');
		}
		
		});
			
/*
$('ul.menu_lvl1').superfish({
	   hoverClass:    'sfHover',
	   pathClass: 'current',
	   delay:       1000,                            // one second delay on mouseout 
       animation:   {opacity:'show',height:'show'},  // fade-in and slide-down animation 
       speed:       'slow',                          // faster animation speed 
       autoArrows:  false,                           // disable generation of arrow mark-up 
       dropShadows: false         
	 });
*/
	
/*
	jQuery('ul.menu_lvl1 li').toggle(function()
      {
	    jQuery(this).children('ul').slideDown();
		jQuery(this).children('ul').css('display', 'block');
      }, function(){
       jQuery(this).children('ul').slideUp();
	   });
*/
	/* AUTOCOMPLETE */
	if (jQuery) {
		$('#offerSearchForm.ajaxSearchForm #vehicle_type_idId').change(function(){

			$('#offerSearchForm #brand_idId').empty();
			$('#offerSearchForm #brand_idId').append('<option value="0">--</option>');
			$('#offerSearchForm #model_idId').empty();
			$('#offerSearchForm #model_idId').append('<option value="0">--</option>');
			$.getJSON(server_url+'/pobierz-marke/'+$('#offerSearchForm #vehicle_type_idId :selected').val()+'/', function(data){
				$.each(data, function(i,item){
					singleMyItem=item.replace("&","&amp;");
					$('#offerSearchForm #brand_idId').append('<option value="'+i+'">'+singleMyItem+'</option>');
		        });
			})
		});
		$('#offerSearchForm.ajaxSearchForm #brand_idId').change(function(){

			$('#offerSearchForm #model_idId').empty();
			$('#offerSearchForm #model_idId').append('<option value="0">--</option>');
			$.getJSON(server_url+'/pobierz-model/'+$('#offerSearchForm #vehicle_type_idId :selected').val()+'/'+$('#offerSearchForm #brand_idId :selected').val()+'/', function(data){
				$.each(data, function(i,item){
					$('#offerSearchForm #model_idId').append('<option value="'+i+'">'+item+'</option>');
		        });
			})
		});
		
		$('#offerSearchForm.ajaxSearchForm #other_vehicle_type_idId').change(function(){
			$('#offerSearchForm #other_vehicle_subtype_idId').empty();
			$('#offerSearchForm #other_vehicle_subtype_idId').append('<option value="0">--</option>');
			$.getJSON(server_url+'/pobierz-podtyp/'+$('#offerSearchForm #other_vehicle_type_idId :selected').val()+'/', function(data){
				$.each(data, function(i,item){
					$('#offerSearchForm #other_vehicle_subtype_idId').append('<option value="'+i+'">'+item+'</option>');
		        });
			})
		});
		$('#offerSearchForm.partsForm #moto_category_idId').change(function(){
			
		});
		
		$('#offerSearchForm.partsForm #brand_idId').change(function(){
			
			$('#offerSearchForm #model_idId').empty();
			$('#offerSearchForm #model_idId').append('<option value="0">--</option>');
			$.getJSON(server_url+'/pobierz-model-dla-marki/'+$('#offerSearchForm #brand_idId :selected').val()+'/', function(data){
				$.each(data, function(i,item){
					$('#offerSearchForm #model_idId').append('<option value="'+i+'">'+item+'</option>');
		        });
			})
		});
		
		$('#offerSearchForm.partsForm #part_category_1Id').change(function(){
			$('#offerSearchForm #part_category_2Id').empty();
			$('#offerSearchForm #part_category_2Id').append('<option value="0">--</option>');
			$('#offerSearchForm #part_category_3Id').empty();
			$('#offerSearchForm #part_category_3Id').append('<option value="0">--</option>');
			$('#offerSearchForm #brand_idId').empty();
			$('#offerSearchForm #model_idId').empty();
			$('#offerSearchForm #model_idId').append('<option value="0">--</option>');
			$('#offerSearchForm #brand_idId').append('<option value="0">--</option>');
			
			$.getJSON(server_url+'/pobierz-kategorie-czesci/'+$('#offerSearchForm #part_category_1Id :selected').val()+'/', function(data){
				$.each(data, function(i,item){
					$('#offerSearchForm #part_category_2Id').append('<option value="'+i+'">'+item+'</option>');
		        });
			})
			
			$.getJSON(server_url+'/pobierz-marke-kategorii/'+$('#offerSearchForm #part_category_1Id :selected').val()+'/', function(data){
				$.each(data, function(i,item){
					$('#offerSearchForm #brand_idId').append('<option value="'+i+'">'+item+'</option>');
		        });
			})
		});
		$('#offerSearchForm.partsForm #part_category_2Id').change(function(){
			$('#offerSearchForm #part_category_3Id').empty();
			$('#offerSearchForm #part_category_3Id').append('<option value="0">--</option>');
			$.getJSON(server_url+'/pobierz-kategorie-czesci/'+$('#offerSearchForm #part_category_2Id :selected').val()+'/', function(data){
				$.each(data, function(i,item){
					$('#offerSearchForm #part_category_3Id').append('<option value="'+i+'">'+item+'</option>');
		        });
			})
		});
		$('#offerSearchForm #vehicle_type_idId.ajaxVehicleType').change(function(){
			$('#offerSearchForm #engineId').empty();
			$('#offerSearchForm #engineId').append('<option value="0">--</option>');
			$.getJSON(server_url+'pobierz-silniki/'+$('#offerSearchForm #vehicle_type_idId.ajaxVehicleType :selected').val()+'/', function(data){
				$.each(data, function(i,item){
					$('#offerSearchForm #engineId').append('<option value="'+i+'">'+item+'</option>');
		        });
			})
		});
		
	}

	$('.ubrFile').click(function(){
        if (typeof(currentForm) != "undefined") {
            uploadbox = $(this).parent('td').parent('tr').parent('tbody').parent('table').parent('div').parent('div').parent('form').parent('div').parent('div').parent('div');
            if (uploadbox.hasClass('videoUploadForm') && currentForm=='photos') {//switch to video
                max_upload_slots_temp = max_upload_slots;
                max_upload_slots = 1;
                upload_range = 1;
                unactivateUploadBox('photosBox');
                activateUploadBox('videoBox');
                allow_extensions = videoExt;
                currentForm = 'video';
            } else if (!uploadbox.hasClass('videoUploadForm') && currentForm=='video') {//switch to photos
                max_upload_slots = max_upload_slots_temp;
                unactivateUploadBox('videoBox');
                activateUploadBox('photosBox');
                temp = $(this).parent('td').parent('tr').children('td').children('input.ubrFile');
                //upload_range = parseInt(temp.attr('id').split('_')[1]) + 1;
                upload_range = countPhotosSlots();
                allow_extensions = photoExt;
                currentForm = 'photos';
            }
        }
    });


    $('#offer_schoolId.search').change(function(){
        $.getJSON(server_url+'get_classes_for_school/'+$('#offer_schoolId.search :selected').val()+'/', function(data){
                $('#offer_classId.search').empty();
            var notResp = 0;
            $.each(data, function(i,item){
                    $('#offer_classId').append('<option value="'+i+'">'+item+'</option>');
                    notResp ++;
            });
            if(notResp > 1) {
                $('#offer_classId.search').removeAttr('disabled');
            } else {
                $('#offer_classId.search').attr('disabled', 'disabled');
            }
        })

    })
    
    $('#offer_schoolId.add').change(function(){
        $.getJSON(server_url+'get_classes_for_school/'+$('#offer_schoolId,add :selected').val()+'/?only=true', function(data){
            $('#offer_classId.add').empty();
            var notResp = 0;
            $.each(data, function(i,item){
                    $('#offer_classId.add').append('<option value="'+i+'">'+item+'</option>');
                    notResp ++;
            });
            if(notResp > 1) {
                $('#offer_classId.add').removeAttr('disabled');
            } else {
                $('#offer_classId.add').attr('disabled', 'disabled');
            }
        })

    })
    
    $('#offer_transactionId.add').change(function(){
        var sub = window.location.hostname.split(".");
        var subdomain;
        var state_id_subdomain = null;
        if(sub.length > 1) {
            if (sub[1] != 'pl') {
                subdomain = sub[0];
                $.getJSON(server_url+'get_state_id_for_subdomain/'+subdomain+'/', function(data2){
                    state_id_subdomain = parseInt(data2);
                })
            }
        }

        $.getJSON(server_url+'get_states_for_transaction/'+$('#offer_transactionId,add :selected').val()+'/', function(data){
            $('#offer_state_idId.add').empty();
            var notResp = 0;
            $.each(data, function(i,item){
                if (state_id_subdomain != null) {
                    if (i == state_id_subdomain) {
                        $('#offer_state_idId.add').append('<option value="'+i+'" selected="selected">'+item+'</option>');
                    }else{
                        $('#offer_state_idId.add').append('<option value="'+i+'" disabled="disabled">'+item+'</option>');
                    }
                } else {
                    $('#offer_state_idId.add').append('<option value="'+i+'">'+item+'</option>');
                }
                notResp ++;
            });
            if(notResp > 1) {
                $('#offer_state_idId.add').removeAttr('disabled');
            } else {
                $('#offer_state_idId.add').attr('disabled', 'disabled');
            }
        })

    })
	
}); //end ready function

function redirect(there){
    window.location = there;
}

function preprareLinkText(text) {
	text = text.toLowerCase();
	text = text.replace(' ', '_');
	text = text.replace('ą', 'a');
	text = text.replace('ó', 'o');
	text = text.replace('ę', 'e');
	text = text.replace('ś', 's');
	text = text.replace('ż', 'z');
	text = text.replace('ź', 'z');
	text = text.replace('ć', 'c');
	text = text.replace('ń', 'n');
	text = text.replace('ł', 'l');
	return text;
}


function addErr(err) {
	//alert(err);
	$('.dialogErrBox').html('');
	$('.dialogErrBox').remove('');
	
	dialogErrBox="<div class='dialogErrBox'>"+err+"</div>"
	
	$('#blockDialog').append(dialogErrBox);
}

function addMsg(msg) {
	$('.dialogErrBox').html('');
	$('.dialogErrBox').remove('');
	
	dialogErrBox="<div class='dialogErrBox dialogMsgBox'>"+msg+"</div>"
	
	$('#blockDialog').append(dialogErrBox);
}

function showNotifyFriendForm(offer_key, link) {
	if (jQuery.ui && jQuery().dialog) {
			var div = '\
				<div class="ui-widget" id="blockDialog">\
					<div style="padding: 0.1em 0.7em; margin-top: 1em;" class="ui-corner-all"> \
						<p><label for="notifyFriendEmail" style="padding-bottom:5px;">'+$write_email+'</label><div class="clear"> </div>\
						<p><span style="float: left; margin-right: 0.3em;" class="ui-icon ui-icon-info"/>\
						<input type="text" id="notifyFriendEmail"/></p>\
					</div>\
				</div>'
			$('body').append(div);
			var buttons = {};
				buttons[$notify]= function(){
						email = $('#notifyFriendEmail').val();
						if (email) {
							$.post(server_url + link + '/'+offer_key+'/powiadom-znajomego/',
									{email: email},
									function(data) {
										answer = data.split('|');
										if (answer && answer[0] == 'MSG') {
											//$('#blockDialog').dialog('destroy');
											//$('#blockDialog').remove();
											addMsg(answer[1]);
											$('#notifyFriendEmail').val('');
										} else {
											addErr(answer[1]);											
										}
							});
						} else {
							addErr($fillCorrectly);//locale.fill_this_form_correctly);
						}
			         };
				buttons[$close] = function(){
						$('#blockDialog').dialog('destroy');
						$('#blockDialog').remove();						
				}
	        $("#blockDialog").dialog({
				autoOpen: false,
			    resizable: false,
				draggable: true,
				width:430,
			    modal: true,
				close: function(event, ui) {
			        $(this).dialog('destroy');
					$(this).remove();
				},
			    title: $notifyAFriend,
			    buttons: buttons
			});
	        $("#blockDialog").dialog('open');

		
	
/* change jQuery button classes */

$('.ui-dialog-buttonpane :button')
    .each(
        function()
        { 
            if($(this).text() == 'close')
            {
               $(this).addClass('closeDialogBtn'); //Do your styling with 'this' object.
            }
        }
    );
	
	}	
}

    
/**
 * prices script
 */

function getPriceSelectsValues(typeId, currencyId, fromId, toId, friendlyLink)
{
    $("select#"+currencyId).change(function(){
        $.getJSON(friendlyLink,{id: $('#'+currencyId).val(), type: $('#'+typeId).val(),  ajax: 'true'}, function(j){
    	var options_od = '';
        for (var i = 0; i < j.length; i++) {
            options_od += '<option value="' + j[i].optionValue_od + '">' + j[i].optionDisplay_od + '</option>';
        }
        var options_do = '';
        for (var i = 0; i < j.length; i++) {
            options_do += '<option value="' + j[i].optionValue_do + '">' + j[i].optionDisplay_do + '</option>';
        }
        $("select#"+fromId).html(options_od);
        $("select#"+toId).html(options_do);
        }) 
    })   
}

function activeIntervalSelect(typeId, currencyId, fromId, toId, friendlyLink)
{
    $("select#"+fromId).change(function(){
        $.getJSON(friendlyLink,{id: $("#"+currencyId).val(), type: $('#'+typeId).val(), selectedKey: $("select#"+fromId).val(), ajax: 'true'}, function(j){
    	var options_od = '';
        var fromVal = $("select#"+fromId).val();
        var toVal = $("select#"+toId).val();
        var selected = '';
        for (var i = 0; i < j.length; i++) {
            if (j[i].optionValue_od == fromVal) {
                selected = 'selected="selected"'
            } else {
                selected = '';
            }
            if (typeof(j[i].optionValue_od) != 'undefined') {
                options_od += '<option value="' + j[i].optionValue_od + '" '+selected+' >' + j[i].optionDisplay_od + '</option>';    
            }
                
        }
        var options_do = '';
        for (var i = 0; i < j.length; i++) {
            if (j[i].optionValue_do == toVal && toVal != 0) {
                selected = 'selected="selected"'
            } else {
                selected = '';
            }
            if (typeof(j[i].optionValue_do) != 'undefined') {
                options_do += '<option value="' + j[i].optionValue_do + '" '+selected+' >' + j[i].optionDisplay_do + '</option>';
            }
            
        }
        $("select#"+fromId).html(options_od);
        $("select#"+toId).html(options_do);
        }) 
    })   
}

function confirmOfferRemove(link){
	var div = '\
		<div class="ui-widget" id="blockDialog">\
			<div style="padding: 0.1em 0.7em; margin-top: 2em;" class="ui-corner-all"> \
				<p><span style="float: left; margin-right: 0.3em;" class="ui-icon ui-icon-info"/>\
				'+$areYouSureYouWantToDeleteChoosenOfferLabel+'</p>\
			</div>\
		</div>'
	$('body').append(div);
    var button = {};
    button[$noLabel] = function(){
        $(this).dialog('destroy');
        $(this).remove();
    };
    button[$yesLabel] = function(){
        window.location = link;
    };
    $("#blockDialog").dialog({

        closeOnEscape: false,
        autoOpen: false,
        resizable: false,
        draggable: false,
        width: 430,
        modal: true,
        close: function(event, ui){
            $(this).dialog('destroy');
            $(this).remove();
        },
        open: function(event, ui) {
        //hide close button.
            $(this).parent().children().children('.ui-dialog-titlebar-close').hide();
        },
        title: $offerDeletionConfirmationLabel,
        buttons: button
    });
    $("#blockDialog").dialog('open');
}
