var popup = {
    hideClass: null,
    courtineId: "courtine",
    courtineOpacity: "0.8",
    courtineZindex: "100",
    courtineBackgroundColor: "#000",
    popupClassName: "popup",
    popupZindex: "120",
    activePopups: {},
    showPopup: function(id, hideClass,opacity){
        if (id in popup.activePopups) {
            return false;
        } else {
            popup.activePopups[id] = true;
        }
	if(arguments[2]){
	    popup.courtineOpacity = opacity;
	}
	if ($("#" + id) && $("#" + id).hasClass(popup.popupClassName)) {
            if ($("#" + id + "> ." + hideClass)) {
                popup.hideClass = hideClass;
                $("#" + id + "> ." + hideClass).click(function(){
                    popup.hidePopup(id);
                    return false;
                })
            }
            $("#" + id).css("z-index", popup.popupZindex);
            popup.hideSelectsForIE6(id);
            popup.popupCourtine();
            popup.justify(id);
	    $("#" + id).show();
	    $("#" + id).find("input").each(function(){
		popup.hideDefaultInputText($(this));
	    })
        }
        return false;
        
        popup.regenerateCaptcha(id);
    },
    hidePopup: function(id){
        delete popup.activePopups[id];
        if ($("#" + id) && $("#" + id).hasClass(popup.popupClassName)) {
            $("#" + popup.courtineId).remove();
            $("#" + id).hide();
            $("select").show();
        }
    },
    popupCourtine: function(){
        var courtine = document.createElement("div");
        courtine.id = popup.courtineId;
        $(courtine).css({
            backgroundColor: popup.courtineBackgroundColor,
            zIndex: popup.courtineZindex,
            position: "absolute",
            top: "0",
            left: "0",
            opacity: popup.courtineOpacity,
            width: $(document).width() + "px",
            height: $(document).height() + "px"
        })
        document.body.appendChild(courtine);
    },
    justify: function(id){
        if ($("#" + id) && $("#" + id).hasClass(popup.popupClassName)) {
            var popupHeight = $("#" + id + "." + popup.popupClassName).height()
            var popupWidth = $("#" + id + "." + popup.popupClassName).width()
            var winDimensions = popup.getPageSize();
            var topPosition = $(document).scrollTop() + ((winDimensions[3] - popupHeight) / 2);
            var leftPosition = $(document).scrollLeft() + ((winDimensions[2] - popupWidth) / 2);

            $("#" + id).css({
                top: topPosition + "px",
                left: leftPosition + "px"
            })
        }
    },
    hideSelectsForIE6: function(eId){
        if ($.browser.msie && 6 < parseInt($.browser.version) < 7) {
            $("select").each(function(){
                $(this).hide();
            });
            $("#" + eId).find("select").each(function(){
                $(this).show();
            })
        }
    },
    getPageSize: function(){
        var xScroll, yScroll;
        if (window.innerHeight && window.scrollMaxY) {
            xScroll = document.body.scrollWidth;
            yScroll = window.innerHeight + window.scrollMaxY;
        }
        else
            if (document.body.scrollHeight > document.body.offsetHeight) {
                // all but Explorer Mac
                xScroll = document.body.scrollWidth;
                yScroll = document.body.scrollHeight;
            }
            else {
                // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
                xScroll = document.body.offsetWidth;
                yScroll = document.body.offsetHeight;
            }
        var windowWidth, windowHeight;
        if (self.innerHeight) {
            // all except Explorer
            windowWidth = self.innerWidth;
            windowHeight = self.innerHeight;
        }
        else
            if (document.documentElement && document.documentElement.clientHeight) {
                // Explorer 6 Strict Mode
                windowWidth = document.documentElement.clientWidth;
                windowHeight = document.documentElement.clientHeight;
            }
            else
                if (document.body) {
                    // other Explorers
                    windowWidth = document.body.clientWidth;
                    windowHeight = document.body.clientHeight;
                }
        // for small pages with total height less then height of the viewport
        if (yScroll < windowHeight) {
            pageHeight = windowHeight;
        }
        else {
            pageHeight = yScroll;
        }
        // for small pages with total width less then width of the viewport
        if (xScroll < windowWidth) {
            pageWidth = windowWidth;
        }
        else {
            pageWidth = xScroll;
        }
        arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight)
        return arrayPageSize;
    },
	hideDefaultInputText: function(e){
		var oldText = null;
		var focusNo = null;
		$(e).focus(function(){
			if(focusNo==null){
				focusNo+=1;
				oldText = $(this).val();
				$(this).val("");
			}else{
				if($(this).val()==oldText){
					$(this).val("");
				}
			}
		})
		$(e).blur(function(){
			if($(this).val()==""){
				$(this).val(oldText);
			}
		})
	},
    regenerateCaptcha: function(id) {
    	$('#'+id+'_captcha').attr('src', '/captcha.png?z='+Math.floor(Math.random()*1000001));
    	$('#'+id+'_captcha_input').val('');
    }
}

var lists = {
	how_many: 5,
	li_list: [],
	show_logn_list_class: "show_hide",
	more_li_className: "more",
	less_li_className: "less",
	more_text: "(+more)",
	less_text: "(-less)",
	customise_ul: function(cls){
		var li = document.createElement("li");
		li.className = lists.show_logn_list_class;
		var ul = document.createElement("ul");
		$(li).appendTo($("."+cls));
		$(ul).appendTo($(li));
		for(var i=lists.how_many; i<lists.li_list.length; i++){
			$(lists.li_list[i]).clone().appendTo($(ul));
			$(lists.li_list[i]).remove();
		}
	},
	listHide: function(cls){
		$("."+cls+" ."+lists.show_logn_list_class).hide();
		$("."+cls+" ."+ lists.less_li_className).hide();
		$("."+cls+" ."+ lists.more_li_className).show();
	},
	listShow: function(cls){
		$("."+cls+" ."+lists.show_logn_list_class).show();
		$("."+cls+" ."+ lists.less_li_className).show();
		$("."+cls+" ."+ lists.more_li_className).hide();
	},
	init: function(cls){
		lists.li_list = $('.'+cls).find('li');
		if(lists.li_list.length > lists.how_many){
			lists.customise_ul(cls);
			lists.insert_more_link(cls);
		}
		lists.listHide(cls);
	},
	insert_more_link: function(cls){
		var more = document.createElement('li');
		var less = document.createElement('li');
		var morelink = document.createElement('a');
		var lesslink = document.createElement('a');
		morelink.href = '#';
		lesslink.href = '#';
		more.className = lists.more_li_className;
		less.className = lists.less_li_className;
		$(more).appendTo($("."+cls));
		$(less).appendTo($("."+cls));
		$(morelink).appendTo($(more));
		$(lesslink).appendTo($(less));
		morelink.innerHTML = lists.more_text;
		lesslink.innerHTML = lists.less_text;
		$("."+cls+" ."+ lists.more_li_className+" a").click(function(){
			lists.listShow(cls);
			return false;
		})
		$("."+cls+" ."+ lists.less_li_className+" a").click(function(){
			lists.listHide(cls);
			return false;
		})
		$(less).hide();
	}
}

/* copytext */
function moveCopyTextToFooter() {
    var head = document.getElementById("copy_top");
    var foot = document.getElementById("copy_bottom");
    foot.innerHTML = head.innerHTML;
    head.style.display = "none";
}

function focusSeccondInput()
{
  try
  {
    var ins = $('input:text:not([onclick])')
    if (ins.length > 1)
      ins[1].focus()
    else
      ins[0].focus()
  }
  catch (e) {} // some ie bug
}

function focusTitleInput() {
  try {
	   if( $('#id_title') ){
	       $('#id_title').focus();
	       /*scrollTo(0,0);*/
	   };
  }
  catch (e) {} // some ie bug
}

function IE6imgMaxWidthFix(imgParentElement,imgMaxWidth){
	if($.browser.msie && $.browser.version=="6.0"){
	    $(imgParentElement).each(function(){
	        $(this).find("img").each(function(){
	            if($(this).width()>imgMaxWidth){
	                $(this).css({
	                   "width":imgMaxWidth+"px"
	                });
	            }
	            $(this).show();
	        });
	    });
	}
}



function query_limit(){
	var limit = 1000;
	var word_limit = 10;

	$("input[name='query']").each(function(){
		$(this).keyup(function(){
			if ($(this).val().length > limit){
				alert("Search query is limited to 10 words or 1000 characters. Please modify your query.");
				$(this).val($(this).val().substring(0,limit));
			}else if($(this).val().split(" ").length > word_limit){
				alert("Search query is limited to 10 words or 1000 characters. Please modify your query.")
				$(this).val($(this).val().substring(0,$(this).val().split('').length - 1));
			}
		})
	})
}

function showMessage(msg, append, className) {
    var messages = $('#messages');
    if (!append) {
        messages.empty();
    }
    if (!messages.length) {
        messages = $('<ul id="messages"></ul>');
        messages.prependTo($('#sessionMessages'));
    }
    var message = $('<li></li>');
    message.addClass(className? className: 'notice');
    message.text(msg);
    message.appendTo(messages);
}

$(document).ready(function() {
    var moderationForm = $('#moderation_form');
    var submitBtn = moderationForm.find('input[type=submit]');
    var reasonSelect = $('#id_reason');

    reasonSelect.change(function() {
        submitBtn.attr('disabled', this.selectedIndex == 0);
    }).change();

    moderationForm.submit(function(event) {
        var self = $(this);
        var formData = {};
        $.each(self.serializeArray(), function(key, value) {
            formData[value.name] = value.value;
        });
        if (formData['reason']) {
            submitBtn.attr('disabled', true);
            $.ajax({
                'url': self.attr('action'),
                'type': 'POST',
                'data': formData,
                'dataType': 'json',
                'error': function(xhr, status, e) {
                    showMessage('Error occured.', false, 'error');
                },
                'success': function(data, status) {
                    showMessage(data['message'], false, data['error']? 'error' : 'notice');
                },
                'complete': function(xhr, status) {
                    submitBtn.attr('disabled', false);
                }
            });
        }
        popup.hidePopup('moderation');
        event.preventDefault();
        return false;
    });

    window.showReportForm = function(advert_id) {
        reasonSelect.attr('selectedIndex', 0).change();
        moderationForm.attr('action', '/sensiads/' + advert_id + '/request_moderation/');
        popup.showPopup('moderation');
    };
});

$(document).ready(function() {
    $('.activateReportElement').each(function() {
        var $control_box = $('.control-box', this);
        var advert_id = $('.advert_id', $control_box).text();
        $('.reportActivator', this).click(function() { showReportForm(advert_id); });
    });
});
