//
// Ads
//
; (function(window) {

    /**
    * Ads Object
    **/
    window.Ads = Ads = new Object();

    /*#region Ads -> List*/
    Ads.List = function() {

        /*******************************
        Variables
        */
        var self = this;
        var categoryCheckList = [];
        var checkedCategories = 0;

        /* slider plugin - needs to be moved to a different .js - maybe in the global section*/
        (function($) {

            $.fn.easySlider = function(options) {

                // default configuration properties
                var defaults = {
                    prevId: 'prevBtn',
                    prevText: 'Previous',
                    nextId: 'nextBtn',
                    nextText: 'Next',
                    orientation: '', //  'vertical' is optional;
                    speed: 500
                };

                var options = $.extend(defaults, options);

                return this.each(function() {
                    obj = $(this);
                    var s = $("li", obj).length;
                    var w = obj.width();
                    var h = obj.height();
                    var ts = s - 1;
                    var t = 0;
                    var vertical = (options.orientation == 'vertical');
                    $("ul", obj).css('width', s * w);
                    if (!vertical) $("li", obj).css('float', 'left');
                    $("#" + options.prevId).addClass('disabled');

                    $("#" + options.nextId).click(function() {
                        if (!$(this).hasClass('disabled')) {
                            animate("next");
                            if (t >= ts) $(this).addClass('disabled');
                            $("#" + options.prevId).removeClass('disabled');
                        }

                    });

                    $("#" + options.prevId).click(function() {
                        if (!$(this).hasClass('disabled')) {
                            animate("prev");
                            if (t <= 0) $(this).addClass('disabled');
                            $("#" + options.nextId).removeClass('disabled');
                        }
                    });

                    function animate(dir) {

                        if (dir == "next") {
                            t = (t >= ts) ? ts : t + 1;
                        } else {
                            t = (t <= 0) ? 0 : t - 1;
                        };
                        if (!vertical) {
                            p = (t * w * -1);
                            $("ul", obj).animate(
						{ marginLeft: p },
						options.speed
					);
                        } else {
                            p = (t * h * -1);
                            $("ul", obj).animate(
						{ marginTop: p },
						options.speed
					);

                        }
                    };
                    if (s > 1) $("#" + options.nextId).css('visibility', 'visible');
                });

            };

        })(jQuery);

        /*end plugin*/
        /*******************************
        Page actions
        */
        var search = function() {

            var localSearchCategories = "";
            var sendSearchCategories = "";
            var onlyPhotos = "false";
            var onlyVideos = "false";


            $("#submenu-bar div.inner").find('a').each(function() {
            	var ctg = '';
            	if ($(this).attr('id') != 'all')
            		ctg = $(this).attr('id').substring(3);
            	else
            		ctg = $(this).attr('id');
            	
                localSearchCategories += ctg + ",";
            });

            var categories = localSearchCategories.substring(4, localSearchCategories.length - 1);
            var searchWord = $("#searchWordInput").attr('value').toString();
           
            if($.trim(searchWord) != "" && searchWord != "search ads")
            {
                window.location = adSearchUrl + '?searchWord=' + searchWord + '&searchCategories=' + categories;
            }

        };

        /*******************************
        Handlers
        */

        //it's called every time the previous/next button is clicked
        var onNextButtonClick = function(pageCount) {

            window.location = adListUrl + "?categoryId=" + category.toString() + "&classNo=" + noOfAdsSelected + "&page=" + pageNumber + "&display=" + display;
        };


        //clicking on an item, displays a page with details about that item
        var onImageClick = function(imageSender) {

            imageSender.children("a").click();
            return false;
        };

        var advancedSearchClicked = function() {

            $(this).toggleClass('selected');
            $("#complexSearchDiv").toggle();

        };

        var minInputBlur = function() {
            var minValue = $(this).attr('value');
            if (minValue != "" && minValue != "min") {
                $(this).addClass('complete');
            }
        };

        var maxInputBlur = function() {
            var maxValue = $(this).attr('value');
            if (maxValue != "" && maxValue != "max") {
                $(this).addClass('complete');
            }
        };

        var searchButtonClicked = function() {

        var localSearchCategories = "";
        var sendSearchCategories = "";
        var onlyPhotos;
        var onlyVideos;

        $("div.result h2 span").html($("#searchInput").attr('value'));

        $("#categorySearchList").find('div[id*=check]').each(function() {

            if ($(this).hasClass('checked') && $(this).attr("id") != "checkAll") {

                var thisCheck = $(this).attr('id').toString();
                localSearchCategories += thisCheck.substring(5, thisCheck.length) + ",";
            }
            pageNumber = 0;

            $("a[name=prev]").hide();
        });

        sendSearchCategories = localSearchCategories.toString().substring(0, localSearchCategories.length - 1);

        if (sendSearchCategories.toString() == "") {

            var allCategories = "";
            $("#categorySearchList").find('div[id*=check]').each(function() {
                if ($(this).attr("id") != "checkAll") {
                    var thisCheck = $(this).attr('id').toString();
                    allCategories += thisCheck.substring(5, thisCheck.length) + ",";
                }
            });

            sendSearchCategories = allCategories.toString().substring(0, allCategories.length - 1);
        }

        if ($("#imageOptionCheck").hasClass('checked') == true) {
            onlyPhotos = "true";
        }
        else {
            onlyPhotos = "false";
        }

        if ($("#videoOptionCheck").hasClass('checked') == true) {
            onlyVideos = "true";
        }
        else {
            onlyVideos = "false";
        }


        var minMax = $("#minInput").val().toString().trim() + "," + $("#maxInput").val().toString().trim();

        if ($("#minInput").val() == "min" || $("#minInput").val() == "" || parseInt($("#minInput").val()) >= 0) {

            if ($("#maxInput").val() == "max" || $("#maxInput").val() == "" || parseInt($("#maxInput").val()) >= 0) {


                $("#maxInput").removeClass('error');
                $("#minInput").removeClass('error');
                $("p.for-price").show();
                $("p.error").hide();

                var searchWord = $("#searchInput").attr('value').toString();

                window.location = adSearchUrl + '?searchWord=' + searchWord + '&onlyPhotos=' + onlyPhotos + '&onlyVideos=' + onlyVideos + '&searchCategories=' + sendSearchCategories + '&minMaxPrice=' + minMax;

            } else {
                $("#maxInput").addClass('error');
                $("#maxInput").removeClass('complete');
                $("p.for-price").hide();
                $("p.error").show();
            }
        } else {

            $("#minInput").addClass('error');
            $("#minInput").removeClass('complete');
            $("p.for-price").hide();
            $("p.error").show();

        }

        };

        /*******************************
        Initialize everything
        */
        (this.Init = function() {
        	 if (totalAds <= noOfAdsSelected) {
                 $(".pagination").hide();
             }
        	
            $('.item img').each(function(){
                if ($(this).attr('src') == '')
                    $(this).attr('src', defaultArticleIconPath);
            });

            var uicombo = new PipenoUI.ComboBox($("#display:first"));

            $(uicombo).bind("change", function(event, oldValue, newValue) {

                display = newValue;
                window.location = adListUrl + "?categoryId=" + category.toString() + "&classNo=" + noOfAdsSelected + "&page=" + pageNumber + "&display=" + display;

            });
            var uicombo = new PipenoUI.ComboBox($(".sort:first"));
            var checkAll = new PipenoUI.CheckBox($("#checkAll"), { checked: true });
            var imageOption = new PipenoUI.CheckBox($("#imageOptionCheck"));
            var videoOption = new PipenoUI.CheckBox($("#videoOptionCheck"));
            var checkedCategories = 0;

            $(uicombo).bind("change", function(event, oldValue, newValue) {

                sortMethod = newValue;
                window.location = adSearchUrl + "?srchNo=" + noOfAdsSelected + "&srchPage=" + pageNumber + "&srchDisplay=" + display + "&sort=" + sortMethod;

            });

            //take from search
            $("#categorySearchList").find('div[id*=check]').each(function() {

                if ($(this).attr("id") != "checkAll") {

                    var categoryCheck = new PipenoUI.CheckBox($(this));

                    categoryCheckList.push(categoryCheck);

                    var categId = $(this).attr('id').toString().substring(5);

                    if ($(this).attr("id") != "checkAll") {
                        if (searchCategories.indexOf(categId) != -1) {

                            categoryCheck.Check(true);
                        }
                        else {
                            checkAll.Check(false);
                        }
                    }

                    $(categoryCheck).bind("change", function(evt, checked) {

                        checkedCategories = 0;

                        $.each(categoryCheckList, function(index, value) {
                            if (categoryCheckList[index].IsChecked()) {
                                checkedCategories++;
                            }
                        });

                        if (checkedCategories == searchCategoriesNumber) {
                            if (checkAll.IsChecked() == false) {
                                checkAll.Check(true);
                            }
                        } else if (checkAll.IsChecked()) {
                            checkAll.Check(false);
                        }


                    });

                }
            });

            $(checkAll).bind("change", function(evt, checked) {

                $.each(categoryCheckList, function(index, value) {

                    if (checked == true) {

                        categoryCheckList[index].Check(true);

                    } else {

                        if (checkedCategories == searchCategoriesNumber || checkedCategories == 0) {
                            categoryCheckList[index].Check(false);
                            checkedCategories = 0;
                        }
                    }
                });

            });

            $(".ads div.search").hide();
            $(".ads-gallery div.search").hide();
            $("#complexSearchDiv").hide();

            if (totalAds == 0) {

                $(".ads div.search").show();
                $(".header").hide();
                $(".featured-aeds").hide();
            }

            if (totalAds <= noOfAdsSelected) {
                $(".pagination").hide();
            }

            if (display == "l") {
                $("#display div").html("List View");
            } else {
                $("#display div").html("Gallery View");
            }

            $("#noResult").hide();
            $("div.inner a#ctg" + category).addClass('selected');
            $("div.header h1").html($("div.inner a#" + category).html());
            $("#searchOptionsButton").bind("click", advancedSearchClicked);

            $("#minInput").bind("blur", minInputBlur);

            $("#maxInput").bind("blur", maxInputBlur);

            $("div.price input").click(function() {
                $(this).attr('value', "");
            });

            $("#searchButton").bind("click", searchButtonClicked);

            $("#searchWordInput").click(function() {

                $(this).attr('value', "");
            });

            $('#searchWordInput').keypress(function(event) {
                 var charCode;

                if (event && event.which) {
                    charCode = event.which;
                } else if (window.event) {
                    event = window.event;
                    charCode = event.keyCode;
                }
            if (charCode == '13') {
                    search();
                }
            });

            $("#menu-bar div.search a").click(function() {
                search();
                return false;
            });

            $("#nextSlideButton").click(function() {

                $("#slideContainer").hide('slide', { direction: 'left' }, 1);
                $("#slideContainer").show('slide', { direction: 'right' }, 2000);

            });

            $("#prevSlideButton").click(function() {

                $("#slideContainer").hide('slide', { direction: 'right' }, 1);
                $("#slideContainer").show('slide', { direction: 'left' }, 2000);
            });

            $(".slide-container").easySlider({

                orientation: 'horizontal'
            });


            $('#searchWordInput').blur(function() {

                if ($(this).attr('value') == "") {
                    $(this).attr('value', "search ads");
                }

            });

            $("#pagination").pagination(totalAds, { items_per_page: 10,
                num_display_entries: 5,
                current_page: pageNumber - 1,
                num_edge_entries: 1,
                link_to: adListUrl + "?categoryId=" + category.toString() + "&classNo=" + noOfAdsSelected + "&page=__id__&display=" + display,
                prev_text: prevText,
                next_text: nextText,
                ellipse_text: "...",
                prev_show_always: true,
                next_show_always: true,
                callback: function(page_index, jq) { }
            });

        })();

    };
    /*#endregion*/

})(window);
/* End Of File */
