jQuery(function($) {
	$(window).load(function () {
		$('#adContentTextAreaBtn').click(function(){
			$.neobizzShowAddDialog();
		});
		$('#neobizz_add_menu').click(function(){
			$.neobizzShowAddDialog();
		});
    	$('a.neobizz_app_link_edit_11').click(function(){
    		$.getNeobizzEditForm(eval('('+$(this).attr('data')+')'));
        });
	});
});

moreSubCategories = function(categoryId) {
    $('more' + categoryId).hide();
    $('less' + categoryId).show();

    $$('#subCategoryList' + categoryId + ' .hidden_subcategory').each(function(e) {
        Effect.Appear(e.id, {duration: 1.0});
    });
}

lessSubCategories = function(categoryId) {
    $('less' + categoryId).hide();
    $('more' + categoryId).show();

    $$('#subCategoryList' + categoryId + ' .hidden_subcategory').each(function(e) {
        Effect.Fade(e.id, {duration: 0.2});
    });
}

moreCategories = function() {
    $('moreCategories').hide();
    $('lessCategories').show();
    Effect.Appear('moreCategoriesContainer', {duration: 1.0});
}

lessCategories = function() {
    $('lessCategories').hide();
    Effect.Fade('moreCategoriesContainer', {duration: 0.2});
    $('moreCategories').show();
}

previousAdImage = function() {
    var x = parseInt($('adImageContainer').style.left.replace('px', ''));
    if (Math.abs(x) > 0 && Math.abs(x % 139) != 0) {
        return false
    }

    if (!x || x == 0) {
        return false;
    }

    new Effect.Move('adImageContainer', { x: 139, y: 0, mode: 'relative', duration:0.4 });
}

nextAdImage = function() {
    var x = parseInt($('adImageContainer').style.left.replace('px', ''));
    var width = parseInt($('adImageContainer').style.width.replace('px', ''));
    if (Math.abs(x) > 0 && Math.abs(x % 139) != 0) {
        return false
    }

    if ((width - Math.abs(x)) / 139 <= 4) {
        return false;
    }


    new Effect.Move('adImageContainer', { x: -139, y: 0, mode: 'relative', duration:0.4 });
}

askYourFriends = function(questionId, adId, adUserId) {
    var content = $('question').getValue();
    $('question').value = '';
    
    var containerId = 'customQuestion';
    
    if (questionId > 0) {
        content = $('questionContent' + questionId).innerHTML;
        containerId = 'question' + questionId;
    } else {
        if (content == '') {
            return;
        }

        content = escape(content);
        Effect.toggle('customQuestionContainer', 'appear', { duration: 0.1 });
    }
    
    $(containerId).innerHTML = lang['29850_sending'];
    $(containerId).addClassName('neobizz_app_question_sent_message');

    var url = NEOBIZZ_URL + 'ajax/send-question/';
   	new Ajax.Request(url, {
		method: 'post',
        postBody: $H({content: content, adId: adId, adUserId: adUserId}).toQueryString(),
		onSuccess: function(transport) {
            var response = transport.responseText.evalJSON();

            if (!response || !response.type) {
                $(containerId).addClassName('neobizz_app_question_sent_message_error');
                $(containerId).innerHTML = 'Error!';

                if (response) {
                    $(containerId).innerHTML = response.message;
                }
                
                return;
            }

            $(containerId).innerHTML = response.message;
		}
	});
}

toggleCustomQuestion = function() {
    Effect.toggle('customQuestionContainer', 'appear', { duration: 0.5 });
}

toggleContactAdOwner = function() {
    Effect.toggle('contactAdOwnerContainer', 'appear', { duration: 0.5 });
}

contactAdOwner = function(toUserId) {
    var message = $('contactMessage').getValue().strip();

    if (message.blank()) {
        systemMessenger.set(lang['30143_empty_message'], 0);
        systemMessenger.display();
        return false;
    }
    
    var url = NEOBIZZ_URL + 'ajax/send-message/';
   	new Ajax.Request(url, {
		method: 'post',
        postBody: $H({message: message, toUserId: toUserId}).toQueryString(),
		onSuccess: function(transport) {
            var response = transport.responseText.evalJSON();

            if (!response) {
                return false;
            }

            systemMessenger.set(response.message, response.type);
            systemMessenger.display();

            $('contactMessage').value = '';
		}
	});

    Effect.toggle('contactAdOwnerContainer', 'appear', { duration: 0.5 });
}


function setNeobizzAdsOrder(order){
    if(order == ""){
        return;
    }
    strLocation = (String)(document.location);
    arWords = Array();
    arWords = strLocation.split("/");
    
    orderIndex = -1;
    for(i=0; i<arWords.length; i++){
        if(arWords[i] == 'order'){
            orderIndex = i;
        }
    }
    
    if(orderIndex != -1){
        arWords.splice(orderIndex+1,1,order);
    }else{
        arWords.push('order');
        arWords.push(order);
    }
    
    document.location = arWords.join("/");
    
}

function submitSearch(actionPath, idCategory, searchString, idCity){
    //searchString = searchString.replace(" ","-");
    document.location = actionPath+"c/"+idCategory+"/cityId/"+idCity+"/search/"+searchString;
}

selectAllMyAds = function() {
    $$('#adsContainer .ad').each(function(element) {
        element.checked = true;
    });
}

deselectAllMyAds = function() {
    $$('#adsContainer .ad').each(function(element) {
        element.checked = false;
    });
}

changeAdState = function(id, state) {
    $('activeStatus' + id).style.display = 'none';
    $('suspendStatus' + id).style.display = 'none';
    $('expireStatus' + id).style.display = 'none';
    $('warningStatus' + id).style.display = 'none';
    $('activateLink' + id).style.display = 'none';
    $('suspendLink' + id).style.display = 'none';

    if (state == 'activate') {
        $('activeStatus' + id).style.display = 'block';

        $('suspendLink' + id).style.display = 'block';

        return true;
    }

    $('suspendStatus' + id).style.display = 'block';
    $('activateLink' + id).style.display = 'block';

    return true;
}

changeMyAdsState = function(state, id) {
    var adIds = new Array();
    var i = 0;
    var ids = id;
    
    if (!id) {
        $$('#adsContainer .ad').each(function(element) {
            if (element.checked) {
                adIds[i] = $(element).getValue();
                i++;
            }
        });
        
        ids = adIds.join(',');
    }

    if (!ids) {
        return;
    }

    var url = NEOBIZZ_URL + 'ajax/suspend-my-ads/';

    if (state == 'activate') {
        url = NEOBIZZ_URL + 'ajax/activate-my-ads/';
    }
    
    new Ajax.Request(url, {
        method: 'post',
        postBody: $H({ids: ids}).toQueryString(),
        onSuccess: function(transport) {
            deselectAllMyAds();
            var ids = transport.responseText.evalJSON();

            if (!ids) {
                return;
            }

            for(var i = 0; i < ids.length; i++) {
                changeAdState(ids[i], state);
            }
        }
    });
}

deleteMyAds = function(id) {
    var adIds = new Array();

    if (!id) {
        $$('#adsContainer .ad').each(function(element) {
            if (element.checked) {
                adIds.push($(element).getValue());
            }
        });
    } else {
        adIds.push(id);
    }

    if (!confirm(lang['30119_are_you_sure'])) {
        return;
    }

    var url = NEOBIZZ_URL + 'ajax/delete-my-ads/';

    new Ajax.Request(url, {
        method: 'post',
        postBody: $H({ids: adIds.toString()}).toQueryString(),
        onSuccess: function(transport) {
            var ids = transport.responseText.evalJSON();
            if (!ids) {
                return;
            }

            if (ids.length > 0) {
                window.location.reload(true);
            }
        }
    });
}

function submitFilter(idForm, searchString){
    filterString = $(idForm).serialize(); 
    filterArray = filterString.split('&');
    
    actionPath = $(idForm).action;
    
    for(i = 0; i < filterArray.length; i++){
        param = filterArray[i].split('=');
        if(param[0] !='' && param[1] != ''){
            actionPath += "/"+param[0]+"/"+param[1];
        }  
    }
    document.location = actionPath;
       
}

// return the type of value
function getTypeOf(value) {
    var s = typeof value;
    if (s === 'object') {
        if (value) {
            if (value instanceof Array) {
                s = 'array';
            }
        } else {
            s = 'null';
        }
    }
    return s;
}


//returns true if o is an object containing no enumerable members.
function isEmptyObject(o) {
    var i, v;
    if (getTypeOf(o) === 'object') {
        for (i in o) {
            v = o[i];
            if (v !== undefined && getTypeOf(v) !== 'function') {
                return false;
            }
        }
    }
    return true;
}


function  updateSelectAutoModels(idModelsContainer,idSelectContainer, selectedBrandId, selectedModelId){
    if(selectedBrandId <= 0){
        $(idModelsContainer).style.display = 'none';
        $(idSelectContainer).innerHTML = '';
        return false;
    }
    $(idSelectContainer).innerHTML = '<select id="idModel" name="idModel" class="neobixx_app_filter_select"></select>';
    models = autoBrandsArray[selectedBrandId]['models'];
    $('idModel').innerHTML = '<option value="0">'+lang['29909_all']+'</option>';
    if(!isEmptyObject(models)){
        for(i in models){
            //alert(i+" "+models[i]+" "+selectedModelId);
            selected = ((selectedModelId == i)?'selected="selected"':'');
            $('idModel').innerHTML += '<option value="'+i+'" '+selected+'>'+models[i]+'</option>';
        }
    }
    $(idModelsContainer).style.display = '';
}

updateMyAd = function() {
    var url = NEOBIZZ_URL + 'ajax/update-my-ad/';
   	new Ajax.Request(url, {
		method: 'post',
        postBody: $('updateMyAdForm').serialize(),
		onSuccess: function(transport) {
            var response = transport.responseText.evalJSON();

            if (!response) {
                return false;
            }

            systemMessenger.set(response.message, response.type);
            systemMessenger.display();

            if (response.type == 1) {
                setTimeout(function(){
                    window.location = response.redirectUrl;
                }, 2000);
            }
		}
	});
}

/* functions from adwizard.php */
function selectAdType(type)
{
    var text = document.getElementById("adContentTextArea");
    if(type == "sell")
    {
       
        text.value = lang['29882_i_sell']+" ";
        document.getElementById("sell_button").innerHTML = '<div class="neobizz_app_panel_menu_active_left"></div><div class="neobizz_app_panel_menu_active_middle">'+lang['29882_i_sell']+'</div><div class="neobizz_app_panel_menu_active_right"></div>';
        document.getElementById("buy_button").innerHTML = '<a class="neobizz_app_panel_menu_link" href="#" onclick="selectAdType(\'buy\'); return false;">'+lang['29881_i_buy']+'</a>';
        document.getElementById("rent_button").innerHTML = '<a class="neobizz_app_panel_menu_link" href="#" onclick="selectAdType(\'rent\'); return false;">'+lang['30679_rental_offer']+'</a>';
        document.getElementById("rent_button_search").innerHTML = '<a class="neobizz_app_panel_menu_link" href="#" onclick="selectAdType(\'rent_search\'); return false;">'+lang['30680_rental_search']+'</a>';
        text.focus();
    }
    if(type == "buy")
    {
        text.value = lang['29881_i_buy']+" ";
        document.getElementById("buy_button").innerHTML = '<div class="neobizz_app_panel_menu_active_left"></div><div class="neobizz_app_panel_menu_active_middle">'+lang['29881_i_buy']+'</div><div class="neobizz_app_panel_menu_active_right"></div>';
        document.getElementById("sell_button").innerHTML = '<a class="neobizz_app_panel_menu_link" href="#" onclick="selectAdType(\'sell\'); return false;">'+lang['29882_i_sell']+'</a>';
        document.getElementById("rent_button").innerHTML = '<a class="neobizz_app_panel_menu_link" href="#" onclick="selectAdType(\'rent\'); return false;">'+lang['30679_rental_offer']+'</a>';
        document.getElementById("rent_button_search").innerHTML = '<a class="neobizz_app_panel_menu_link" href="#" onclick="selectAdType(\'rent_search\'); return false;">'+lang['30680_rental_search']+'</a>';
        text.focus();
    }
    if(type == "rent")
    {
        text.value = lang['30685_rental_offer_text']+" ";
        document.getElementById("rent_button").innerHTML = '<div class="neobizz_app_panel_menu_active_left"></div><div class="neobizz_app_panel_menu_active_middle">'+lang['30679_rental_offer']+'</div><div class="neobizz_app_panel_menu_active_right"></div>';
        document.getElementById("rent_button_search").innerHTML = '<a class="neobizz_app_panel_menu_link" href="#" onclick="selectAdType(\'rent_search\'); return false;">'+lang['30680_rental_search']+'</a>';
        document.getElementById("sell_button").innerHTML = '<a class="neobizz_app_panel_menu_link" href="#" onclick="selectAdType(\'sell\'); return false;">'+lang['29882_i_sell']+'</a>';
        document.getElementById("buy_button").innerHTML = '<a class="neobizz_app_panel_menu_link" href="#" onclick="selectAdType(\'buy\'); return false;">'+lang['29881_i_buy']+'</a>';
        text.focus();
    }
    if(type == "rent_search")
    {
        text.value = lang['30686_rental_search_text']+" ";
        document.getElementById("rent_button_search").innerHTML = '<div class="neobizz_app_panel_menu_active_left"></div><div class="neobizz_app_panel_menu_active_middle">'+lang['30680_rental_search']+'</div><div class="neobizz_app_panel_menu_active_right"></div>';
        document.getElementById("rent_button").innerHTML = '<a class="neobizz_app_panel_menu_link" href="#" onclick="selectAdType(\'rent\'); return false;">'+lang['30679_rental_offer']+'</a>';
        document.getElementById("sell_button").innerHTML = '<a class="neobizz_app_panel_menu_link" href="#" onclick="selectAdType(\'sell\'); return false;">'+lang['29882_i_sell']+'</a>';
        document.getElementById("buy_button").innerHTML = '<a class="neobizz_app_panel_menu_link" href="#" onclick="selectAdType(\'buy\'); return false;">'+lang['29881_i_buy']+'</a>';
        text.focus();
    }
}

function fit_to_text(max_height){
    var text = document.getElementById("adContentTextArea");
    text.style.height = 36+"px";
    if(text.scrollHeight < 36){
        text.style.height = 36+"px";
    } else {
        text.style.height = text.scrollHeight+"px";
    }
}
                
    
function focusAdInput()
{
    document.getElementById('wizzard_hidden_content').style.display = '';
    document.getElementById('wizzard_submit_button').style.display = '';
}
    
function hideWizzard()
{
    document.getElementById('wizzard_hidden_content').style.display = 'none';
    document.getElementById('wizzard_submit_button').style.display = 'none';        
}
    
function getSpecs(path, catId, cityId)
{
    if(catId)
    {
        new Ajax.Updater('specs', NEOBIZZ_URL + 'ajax/getspecs',
            {
                asynchronous:true, 
                evalScripts:true, 
                parameters: {catId : catId, cityId : cityId} 
            }
        );
    }
}
    
function addAd(path)
{
    new Ajax.Request(NEOBIZZ_URL + 'ajax/addad',
        {
            asynchronous:true, 
            evalScripts:true, 
            parameters: $('add_ad_form').serialize(true),
            onSuccess: function(transport) {
                eval(transport.responseText);
            } 
        }
    );
}

