/*jQuery.fn.log = function (msg) {
	if ($.browser.mozilla) {
		console.log("%s: %o", msg, this);
	}
	return this;
};*/

(function($) {
    var cache = [];
    // Arguments are image paths relative to the current page.
    $.preLoadImages = function() {
        var args_len = arguments.length;
        for (var i = args_len; i--;) {
            var cacheImage = document.createElement('img');
            cacheImage.src = arguments[i];
            cache.push(cacheImage);
        }
    }
})(jQuery)

function FitToContent(id, maxHeight) {
    var text = id && id.style ? id : document.getElementById(id);
    if (!text) {
        return;
    }

    var adjustedHeight = text.clientHeight;
    if (!maxHeight || maxHeight > adjustedHeight) {
        adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
        if (maxHeight) {
            adjustedHeight = Math.min(maxHeight, adjustedHeight);
        }
        if (adjustedHeight > text.clientHeight) {
            text.style.height = adjustedHeight + "px";
        }
    }
}

function createMarker(point, icon, content, listener, state) {
    var marker = new GMarker(point, icon);
    var html = '<div class="map_popup">';
    html = html + content;
    html = html + '</div>';
	
    if (state == 'open') {
        marker.openInfoWindowHtml(html);
    }
	
    GEvent.addListener(marker, listener, function() {
        marker.openInfoWindowHtml(html);
    });
	
    return marker;
}

function createIcon(image) {
    var icon;
    if (!image) {
        icon = new GIcon(G_DEFAULT_ICON);
    } else {
        icon = new GIcon();
        icon.image = "/images/map/" + image;
        icon.shadow = "/images/map/shadow.png";
        icon.iconSize = new GSize(27.0, 34.0);
        icon.shadowSize = new GSize(45.0, 34.0);
        icon.iconAnchor = new GPoint(13.0, 34.0);
        icon.infoWindowAnchor = new GPoint(13.0, 17.0);
    }
    return icon;
}

function tinymceStart(selector, table, id) {
	
    if ($(selector).length) {
        // Compress
        tinyMCE_GZ.init({
            plugins : "safari,save,iespell,inlinepopups,contextmenu,paste,directionality,noneditable,visualchars,nonbreaking,xhtmlxtras,spellchecker",
            themes : 'advanced',
            languages : 'en',
            disk_cache : true,
            debug : false
        });
	
        // Render
        tinyMCE.init({
            mode : "exact",
            elements : selector,
		
            width : "460",
            height : "450",
		
            theme : "advanced",
            plugins : "safari,save,iespell,inlinepopups,contextmenu,paste,directionality,noneditable,visualchars,nonbreaking,xhtmlxtras,spellchecker",
		
            theme_advanced_buttons1 : "undo,redo,|,bold,italic,bullist,numlist,|,cut,copy,paste,pastetext,pasteword,|,spellchecker,|,help",
            theme_advanced_buttons2 : "",
            theme_advanced_buttons3 : "",
            theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_align : "left",
            theme_advanced_statusbar_location : "bottom",
            //theme_advanced_resizing : true,
		
            spellchecker_languages : "+English=en",
            spellchecker_rpc_url : "/control/scripts/tiny_mce_3_2_7/plugins/spellchecker/rpc.php"
        });
    }
}

/* Shadowbox.init({
    skipSetup: true
}); */

Shadowbox.init({
    skipSetup: true,
    clearCache: function() {
        each(S.cache, function(obj) {
            if( obj.el) {
                S.lib.removeEvent(obj.el, 'click', handleClick);
                try {
                    delete obj.el.shadowboxCacheKey;
                } catch(e) {
                    if (obj.el.removeAttribute) {
                        obj.el.removeAttribute('shadowboxCacheKey');
                    }
                }
            }
        });
        S.cache = [];
    }
});

function key(number) {
    return Math.floor(Math.random() * number);
}

function fetchImages(selector, table, link_name) {
    if ($(selector).length) {
        $(selector).show();
        $.ajax({
            type	: "GET",
            url		: "/images.php",
            data	: "table=" + table + "&link_name=" + link_name + "&key=" + key(10000),
            success	: function(html){
                $(selector).empty();
                $(selector).append(html);
			
                Shadowbox.setup(".popup");

                if (html == '') {
                    $(selector).hide();
                }
            }
        });
    }
}

function fetchInfo(link_name) {
    var selector = '#listing_info';
    if ($(selector).length) {
        $.ajax({
            type	: "GET",
            url		: "/info.php",
            data	: "link_name=" + link_name + "&key=" + key(10000),
            success	: function(html){
                $(selector).empty();
                $(selector).append(html);
            }
        });
    }
}

function fetchCalendar() {
    var selector = '#calendar';
    if ($(selector).length) {
        $.ajax({
            type	: "GET",
            url		: "/calendar.php",
            data	: "key=" + key(10000),
            success	: function(html){
                $(selector).empty();
                $(selector).append(html);
            }
        });
    }
}

function nextMonth() {
    var selector = '#calendar';
    if ($(selector).length) {
        $.ajax({
            type	: "GET",
            url		: "/calendar.php",
            data	: "go=next&key=" + key(10000),
            success	: function(html){
                $(selector).empty();
                $(selector).append(html);
            }
        });
    }
}

function prevMonth() {
    var selector = '#calendar';
    if ($(selector).length) {
        $.ajax({
            type	: "GET",
            url		: "/calendar.php",
            data	: "go=prev&key=" + key(10000),
            success	: function(html){
                $(selector).empty();
                $(selector).append(html);
            }
        });
    }
}

function fetchGallery(gallery_id) {
    // Check if the selector exists before calling the php script
    var selector = '#gallery';
    if ($(selector).length) {
        if (!gallery_id) {
            gallery_id = '';
        }
        $.ajax({
            type	: "GET",
            url		: "/gallery.php",
            data	: "gallery_id=" + gallery_id + "&key=" + key(10000),
            success	: function(html){
			
                $(selector).empty();
                $(selector).append(html);
			
                Shadowbox.clearCache();

                $('#gallery_category_id').change( function() {
                    filterGallery(this);
                });
            }
        });
    }
}

function filterGallery(gallery_category_id, gallery_subcategory_id) {
    var selector = '#gallery';
    if ($(selector).length) {
        if (!gallery_subcategory_id) {
            gallery_subcategory_id = '';
        }
        $.ajax({
            type	: "GET",
            url		: "/gallery.php",
            data	: "gallery_category_id=" + gallery_category_id + "&gallery_subcategory_id=" + gallery_subcategory_id +  "&key=" + key(10000),
            success	: function(html){
			
                $(selector).empty();
                $(selector).append(html);
			
                Shadowbox.clearCache();

            /* $('#gallery_category_id').change( function() {
                filterGallery(this);
            }); */
            }
        });
    }
}

function fetchAlbum(gallery_id, gallery_category_id, gallery_subcategory_id) {
    var selector = '#gallery';
    if ($(selector).length) {
        if (!gallery_subcategory_id) {
            gallery_subcategory_id = '';
        }
        $.ajax({
            type	: "GET",
            url		: "/gallery.php",
            data	: "gallery_id=" + gallery_id + "&gallery_category_id=" + gallery_category_id + "&gallery_subcategory_id=" + gallery_subcategory_id + "&key=" + key(10000),
            success	: function(html){

                $(selector).empty();
                $(selector).append(html);

                Shadowbox.setup(".popup");
            }
        });
    }
}

function fetchAllPhotos() {
    var selector = '#photos';
    if ($(selector).length) {
        $.ajax({
            type	: "GET",
            url		: "/photos.php",
            data	: "key=" + key(10000),
            success	: function(html){
			
                $(selector).empty();
                $(selector).append(html);
			
                Shadowbox.clearCache();
            }
        });
    }
}

function fetchListingPhotos(link_name) {
    var selector = '#photos';
    if ($(selector).length) {
        $.ajax({
            type	: "GET",
            url		: "/photos.php",
            data	: "link_name=" + link_name + "&key=" + key(10000),
            success	: function(html){
			
                $(selector).empty();
                $(selector).append(html);
			
                Shadowbox.setup(".popup");
            }
        });
    }
}

function fetchMenu(selector, position) {
    if ($(selector).length) {
        $.ajax({
            type	: "GET",
            url		: "/menu.php",
            data	: "position=" + position + "&key=" + key(10000),
            success	: function(html){
			
                $(selector).empty();
                $(selector).append(html);
			
                if (position == 'top') {
                    $("ul.sf-menu").supersubs({
                        minWidth:    12,
                        maxWidth:    27,
                        extraWidth:  1
                    }).superfish({
                        dropShadows : false
                    });
                }
			
                if (position == 'left') {
                    $("ul.sf-menu").superfish({
                        dropShadows : false
                    });
                }
			
            }
        });
    }
}

function fetchAdverts(selector, position, page) {
    if ($(selector).length) {
        $.ajax({
            type	: "GET",
            url		: "/adverts.php",
            data	: "page=" + page + "&position=" + position + "&key=" + key(10000),
            success	: function(html){
                $(selector).empty();
                $(selector).append(html);
			
                Shadowbox.setup(".popup");
			
            }
        });
    }
}

function fetchListings(selector, limit) {
    if ($(selector).length) {
        $.ajax({
            type	: "GET",
            url		: "/listings.php",
            data	: "limit=" + limit + "&key=" + key(10000),
            success	: function(html){
                $(selector).empty();
                $(selector).append(html);
            }
        });
    }
}

function fetchLogin(selector, domain, page) {
    if ($(selector).length) {
        $.ajax({
            type	: "POST",
            url		: "/login.php",
            data	: "show=1" +
            "&key=" + key(10000),
            success	: function(html){
                $(selector).empty();
                $(selector).append(html);
                $("input").addClass("ui-widget ui-widget-content ui-corner-all");
                $("input:checkbox").removeClass("ui-widget ui-widget-content ui-corner-all");
                $("input:button").button();
                $("textarea").addClass("ui-widget ui-widget-content ui-corner-all");
                $("#authenticate").click(function () {
				
                    //$("#username").log('USERNAME');
                    //$("#password").log('PASSWORD');
                    //$("#login").log('MD5: ' + md5($("#username").val() + $("#password").val()))
				
                    $.ajax({
                        type	: "POST",
                        url		: "/login.php",
                        data	: "username=" + $("#username").val() +
                        "&password=" + $("#password").val() +
                        "&md5=" + md5($("#username").val() + $("#password").val()) +
                        "&key=" + key(10000),
                        success	: function(authenticated){
						
                            //$("#login").log('AUTHENTICATED: ' + authenticated);
						
                            if (authenticated == 1) {
                                //fetchBasket(); $('#basket').log("basket is shown");
                                $("#login").empty();
                                //$("#login").append('<a href="/login.php?logout=1" target="_self"><img src="/website/styles/default/logout_large.png" alt="logout" width="80" height="30" border="0" /></a> <a href="/page/edit_listings" target="_self"><img src="/website/styles/default/edit_listings_large.png" alt="edit listings" width="160" height="30" border="0" /></a> <a href="/page/edit_profile" target="_self"><img src="/website/styles/default/edit_profile_large.png" alt="edit profile" width="160" height="30" border="0" /></a>');
                                //alert("Thank you. You may now proceed to edit your listings.");
                                alert("Thank you. You are now logged in.");
                                top.location = "http://" + domain + "/index.php?page_name=" + page;
                            } else {
                                alert("ERROR! Please enter your correct username and password.");
                            }
						
                        }
                    });
                });
            }
        });
    }
}

function fetchNews(limit) {
    var selector = '#news';
    if ($(selector).length) {
        $.ajax({
            type	: "GET",
            url		: "/news.php",
            data	: "limit=" + limit + "&key=" + key(10000),
            success	: function(html){
                $(selector).empty();
                $(selector).append(html);
			
                Shadowbox.setup(".popup");
            }
        });
    }
}

function fetchEvents(limit) {
    var selector = '#events';
    if ($(selector).length) {
        $.ajax({
            type	: "GET",
            url		: "/events.php",
            data	: "limit=" + limit + "&key=" + key(10000),
            success	: function(html){
                $(selector).empty();
                $(selector).append(html);
			
                Shadowbox.setup(".popup");
            }
        });
    }
}

function fetchArticles(limit) {
    var selector = '#articles';
    if ($(selector).length) {
        $.ajax({
            type	: "GET",
            url		: "/articles.php",
            data	: "limit=" + limit + "&key=" + key(10000),
            success	: function(html){
                $(selector).empty();
                $(selector).append(html);

                Shadowbox.setup(".popup");
            }
        });
    }
}

function fetchSnippet(type, limit) {
    var selector = '#' + type + '_snippet';
    if ($(selector).length) {
        $.ajax({
            type	: "GET",
            url		: "/" + type + "_snippet.php",
            data	: "limit=" + limit + "&key=" + key(10000),
            success	: function(html){
                $(selector).empty();
                $(selector).append(html);
			
                Shadowbox.setup(".popup");
            }
        });
    }
}

function fetchSlideshow(container, width, height, show_on_all) {
    var selector = '#' + container;
    if ($(selector).length) {
        if (!container) {
            container = '';
        }
        $.ajax({
            type	: "GET",
            url		: "/slideshow.php",
            data	: "width=" + width + "&height=" + height + "&container=" + container + "&show_on_all=" + show_on_all + "&key=" + key(10000),
            success	: function(html){
			
                $(selector).empty();
                $(selector).append(html);
			
                $(selector).cycle({
                    fx:     'fade',
                    timeout: 8000,
                    //next:   '#slideshow',
                    pause:   1,
                    random:  1
                //before:  onBefore,
                //after:   onAfter
                });
            }
        });
    }
}

function fetchBasket() {
    var selector = '#basket';
    if ($(selector).length) {
        $(selector).show();
        $.ajax({
            type	: "GET",
            url		: "/basket.php",
            data	: "&key=" + key(10000),
            success	: function(html){
                $(selector).empty();
                $(selector).append(html);

                if (html == '') {
                    $(selector).hide();
                } else {
                    Shadowbox.setup(".popup");
                }
            }
        });
    }
}

function addToBasket(id, link_name) {
    var selector = '#basket';
    if ($(selector).length) {
        if (!link_name) {
            link_name = '';
        }

        var quantity = Number($('#quantity_' + id).val());
        //var quantity = 1;
        $(selector).show();
        $.ajax({
            type	: "GET",
            url		: "/basket.php",
            data	: "listing_id=" + id + "&quantity=" + quantity + "&key=" + key(10000),
            success	: function(html){
                $(selector).empty();
                $(selector).append(html);
                if (link_name == '') {
                    flash($("#listing_" + id), "#C8D7E7", $("#listing_" + id).css('backgroundColor'));
                } else {
                    flash($("#basket_content"), "#C8D7E7", $("#basket_content").css('backgroundColor'));
                }
                Shadowbox.setup(".popup");
            }
        });
    }
}

function changeShipping(dropdown) {
    var selector = '#basket';
    if ($(selector).length) {
        if (dropdown.value != '') {
            $.ajax({
                type	: "GET",
                url		: "/basket.php",
                data	: "shipping_id=" + dropdown.value + "&key=" + key(10000),
                success	: function(html){
                    $(selector).empty();
                    $(selector).append(html);
                    flash($("#basket_content"), "#C8D7E7", $("#basket_content").css('backgroundColor'));
                    Shadowbox.setup(".popup");
                }
            });
        }
    }
}

function flash(selector, color1, color2) {
    if ($(selector).length) {
        $(selector)
        .animate({
            backgroundColor: color1
        }, 'slow')
        .animate({
            backgroundColor: color2
        }, 'slow')
        .animate({
            backgroundColor: color1
        }, 'slow')
        .animate({
            backgroundColor: color2
        }, 'slow');
    }
}

function removeItem(item_id) {
    var selector = '#basket';
    if ($(selector).length) {
        $.ajax({
            type	: "GET",
            url		: "/basket.php",
            data	: "remove=1&item_id=" + item_id + "&key=" + key(10000),
            success	: function(html){
                $(selector).empty();
                $(selector).append(html);
                Shadowbox.setup(".popup");
            }
        });
    }
}

function emptyBasket() {
    var selector = '#basket';
    if ($(selector).length) {
        $.ajax({
            type	: "GET",
            url		: "/basket.php",
            data	: "empty=1&key=" + key(10000),
            success	: function(html){
                $(selector).empty();
                $(selector).append(html);
            }
        });
    }
}

function emailExists(table, email, form) {
    $.ajax({
        type	: "GET",
        url		: "/check.php",
        data	: "table=" + table + "&email=" + email + "&key=" + key(10000),
        success	: function(response){
            if (response == 1) {
                alert('The email address you entered already exists in our database.');
            } else {
                checkCaptcha(form);
            }
        }
    });
}

function checkFile(selector, allow, form) {
    var allowed = '';
    if ($(selector).length > 0){
        if ($(selector).val() != '') {
            var ext = $(selector).val().split('.').pop().toLowerCase();
            if(jQuery.inArray(ext, allow) == -1) {
                for(var i = 0; i < allow.length; i++){
                    allowed = allowed + ' .' + allow[i];
                }
                alert('You can only upload files with the extension: ' + allowed);
                $(selector).focus();
            } else {
                form.submit();
            }
        } else {
    //alert("Please add your file.");
    //$(selector).focus();
    }
    }
}

function checkCaptcha(form) {
    if ($('#txtCaptcha').val().length == 5) {
        $.ajax({
            type	: "POST",
            url		: "/control/captcha/captcha.php",
            data	: "txtCaptcha=" + document.getElementById("txtCaptcha").value + "&key=" + key(10000),
            success	: function(html){
                //$("#result").empty();
                //$("#result").append(html);
				
                if (html == "FAIL") {
                    alert("The code you entered was incorrect. Please try again.");
                    $("#imgCaptcha").attr("src", "/control/captcha/image.php?key=" + key(10000));
                } else {
                    form.submit();
                }
            }
        });
    } else {
        alert("Please enter the exact code on the image into the text box and try again.");
        document.getElementById("txtCaptcha").focus();
    }
}

function timeDifference(startDate, endDate) {
	
    date2 = startDate;
    date1 = endDate;
	
    laterdate = date1.split("-");
    laterY = laterdate[0];
    laterM = laterdate[1];
    laterD = laterdate[2];
    //alert('end year' + laterY);
	
    earlierdate = date2.split("-");
    earlierY = earlierdate[0];
    earlierM = earlierdate[1];
    earlierD = earlierdate[2];
    //alert('start year' + earlierY);
	
    var laterdate = new Date(laterY,laterM,laterD);
    var earlierdate = new Date(earlierY,earlierM,earlierD);
	
    var difference = laterdate.getTime() - earlierdate.getTime();
	
    //alert(difference);

    var daysDifference = Math.floor(difference / 1000 / 60/ 60 / 24);
    difference -= daysDifference * 1000 * 60 * 60 * 24
    var hoursDifference = Math.floor(difference / 1000 / 60 / 60);
    difference -= hoursDifference * 1000 * 60 * 60
    var minutesDifference = Math.floor(difference / 1000 / 60);
    difference -= minutesDifference * 1000 * 60
    var secondsDifference = Math.floor(difference / 1000);
	
    return daysDifference;

}
