/* Add a unique() method the Array prototype */
Array.prototype.unique = function () {
    var r = new Array();
    o:for( var i=0, n=this.length; i<n; i++ ) {
        for ( var x=0, y=r.length; x<y; x++ ) {
            if ( r[x]==this[i] ) {
                continue o;
            }
        }
        r[r.length] = this[i];
    }
    return r;
};

function qsParamsToArray( str ) {
    var assoc = new Array();
    var keyValues = str.split('&');
    for ( var i=0; i<keyValues.length; i++ ) {
        var key = keyValues[i].split('=');
        assoc[key[0]] = key[1];
    }
    return assoc;
}

/*
 * imgPreview jQuery plugin
 * Copyright (c) 2009 James Padolsey
 * j@qd9.co.uk | http://james.padolsey.com
 * Dual licensed under MIT and GPL.
 * Updated: 09/02/09
 * @author James Padolsey
 * @version 0.22
 */
( function( $ ) {
    $.expr[':'].linkingToImage = function( elem, index, match ) {
    // This will return true if the specified attribute contains a valid link to an image:
        return !! ($(elem).attr(match[3]) && $(elem).attr(match[3]).match(/\.(gif|jpe?g|png|bmp)$/i));
    };
    $.fn.imgPreview = function( userDefinedSettings ) {
        var s = $.extend( {
            /* DEFAULTS */
            // CSS to be applied to image:
            imgCSS:{},
            // Distance between cursor and preview:
            distanceFromCursor:{top:10, left:10},
            // Boolean, whether or not to preload images:
            preloadImages:true,
            // Callback: run when link is hovered: container is shown:
            onShow:function(){},
            // Callback: container is hidden:
            onHide:function(){},
            // Callback: Run when image within container has loaded:
            onLoad:function(){},
            // ID to give to container (for CSS styling):
            containerID:'imgPreviewContainer',
            // Class to be given to container while image is loading:
            containerLoadingClass:'loading',
            // Prefix (if using thumbnails), e.g. 'thumb_'
            thumbPrefix:'',
            // Where to retrieve the image from:
            srcAttr:'rel'
        }, userDefinedSettings ),
        
        $container = $('<div/>').attr( 'id', s.containerID )
            .append('<img/>')
            .hide()
            .css( 'position', 'absolute' )
            .appendTo('body'),
        
        $img = $('img', $container).css(s.imgCSS),
        
        // Get all valid elements (linking to images / ATTR with image link):
        $collection = this.filter( ':linkingToImage(' + s.srcAttr + ')' );
        
        // Re-usable means to add prefix (from setting):
        function addPrefix( src ) {
            return src.replace( /(\/?)([^\/]+)$/, '$1' + s.thumbPrefix + '$2' );
        }
      
        if ( s.preloadImages ) {
            ( function( i ) {
                var tempIMG = new Image(), callee = arguments.callee;
                tempIMG.src = addPrefix( $( $collection[i] ).attr( s.srcAttr ) );
                tempIMG.onload = function() {
                    $collection[i + 1] && callee(i + 1);
                };
            } )(0);
        }
               
        $collection.mousemove( function( e ) {
            $container.css( {
                top: e.pageY + s.distanceFromCursor.top + 'px',
                left: e.pageX + s.distanceFromCursor.left + 'px'
            } );
        } ).hover( function() {
            var link = this;
            $container.addClass(s.containerLoadingClass).show();
            $img.load( function() {
                $container.removeClass( s.containerLoadingClass );
                $img.show();
                s.onLoad.call($img[0], link);
            } ).attr( 'src' , addPrefix($(link).attr( s.srcAttr ) ) );
            s.onShow.call($container[0], link);
            },
            function() {
                $container.hide();
                $img.unbind('load').attr('src','').hide();
                s.onHide.call($container[0], this);
            } );
            
            // Return full selection, not $collection!
            return this;
        };
} )(jQuery);

window.onload = function() {
    // run the home page slideshow
    if ( $('#homeSlideshow').length > 0 ) {
        $('#homeSlideshow').cycle( {
            fx:'fade',
            random:1,
            containerResize:0,
            speed:600,
            timeout:2600,
            height:398 
        } );
    }

    // run any event slideshows
    if ( $('#tomPalmoreShow_ss').length > 0 ) {
        $('#tomPalmoreShow_ss').cycle( {
            fx:'fade',
            random:0,
            containerResize:0,
            speed:600,
            timeout:2600,
            height:292 
        } );
    }
    if ( $('#fallGalleryWalk2009_ss').length > 0 ) {
        $('#fallGalleryWalk2009_ss').cycle( {
            fx:'fade',
            random:0,
            containerResize:0,
            speed:600,
            timeout:2600,
            height:292 
        } );
    }
    if ( $('#dcpgAndBonnieConrad_ss').length > 0 ) {
        $('#dcpgAndBonnieConrad_ss').cycle( {
            fx:'fade',
            random:0,
            containerResize:0,
            speed:600,
            timeout:2600,
            height:292 
        } );
    }
    if ( $('#louisLAmourStories_ss').length > 0 ) {
        $('#louisLAmourStories_ss').cycle( {
            fx:'fade',
            random:0,
            containerResize:0,
            speed:600,
            timeout:2600,
            height:292 
        } );
    }
};

/* Set the height of the sidebarBod container.
   The bottom image, a background of #outerContainer1, is 112px tall. */
function setSidebarHt() {
    var sbBodHt = $("#outerContainer1").height() - $("#sidebarTop").height() - 112;
    $("#sidebarBod").css( {height:sbBodHt + "px"} );
}

$(document).ready( function() {
    $("#newsletterLink").click( function() {
        $("#modalNews").modal( {
		    zIndex:999999,
		    position:[200,],
            overlayClose:true,
		    containerCss:{ backgroundColor:"#e9deca", height:"340px", width:"390px" }
        } );
        return false;
	} );

    $(".modalContactLink").click( function() {
        $("#modalContact").modal( {
		    zIndex:999999,
		    position:[200,],
            overlayClose:true,
		    containerCss:{ backgroundColor:"#e9deca", height:"525px", width:"390px" }
        } );
        return false;
	} );

    $(".adModal").click( function() {
        $("#adPop").modal( {
		    zIndex:999999,
		    position:[200,],
            overlayClose:true,
		    containerCss:{ backgroundColor:"#e9deca", height:"auto", width:"450px" }
        } );
        return false;
	} );

    $(".thumbModal").click( function( evt ) {
        evt.preventDefault();
        var url = $(this).attr('href');
        var qStr = "";
        var href = "";
        var qMarkAt = url.indexOf( "?" );
        if ( qMarkAt != -1 ) {
            href = url.slice( 0, qMarkAt );
            qStr = url.substr( qMarkAt+1 );
        } else {
            href = url;
        }
        var qsArr = qsParamsToArray( qStr );
        var href_array= href.split("/");
        var part_num = 0;
        var imgSrc = "";
        while (part_num < href_array.length) {
            imgSrc = href_array[part_num];
            part_num += 1;
        }
        $('#itemDetailImg').replaceWith( '<img alt="'+qsArr.title + ' by ' + qsArr.name + '" height="' + qsArr.height + '" id="itemDetailImg" src="photos/' + imgSrc + '" width="' + qsArr.width + '" />' );
        var itemDetail = $("#itemDetail").modal( {
            zIndex:999999,
            position:[50,],
            overlayClose:true,
            containerCss:{ backgroundColor:"#e9deca", position:"absolute !important", overflow:"visible" },
            onShow:function() {
                $('#itemDetail_title').text( qsArr.title);
                $('#itemDetail_name').text( qsArr.name);
                $('#itemDetail_medium').text( qsArr.medium);
                $('#itemDetail_size').text( qsArr.size);
                $('#itemDetail_price').text( qsArr.price);
                $('#itemDetail_bcode').text( qsArr.bcode);
            }
        } );
        return false;
    } );

    // special for Ben Nighthorse
    $("#nighthorseCatalogBtn").click( function() {
        $("#modalNighthorseCatalog").modal( {
		    zIndex:999999,
		    position:[200,],
            overlayClose:true,
		    containerCss:{ backgroundColor:"#e9deca", height:"340px", width:"412px" }
        } );
        return false;
	} );

    // position the footer on short pages
    if ( $("#footer.shortPage").length > 0 ) {
        // find the tallest outer column
        var oc1 = $("#outerCol1of2").height();
        var oc2 = $("#outerCol2of2").height();
        var oc = oc1 < oc2 ? oc2 : oc1;
        $("#innerContainer2").css( { height:oc + 60 + 'px' } );
        $("#footer.shortPage").css( { top:oc + 60 + 'px' } );
    }

	setSidebarHt();

    // handle subnav
    $("#navNews").mouseover( function() {
        $(".subcatHide").css( {visibility:"visible"} );
    } );

    $("#navNews").mouseout( function() {
        $(".subcatHide").css( {visibility:"hidden"} );
    } );
    
    $(".subcatHide").mouseover( function() {
        $(".subcatHide").css( {visibility:"visible"} );
    } );

    $(".subcatHide").mouseout( function() {
        $(".subcatHide").css( {visibility:"hidden"} );
    } );
    
    $(".subcatDivider").mouseover( function() {
        $(".subcatHide").css( {visibility:"visible"} );
    } );

    // do image preview on thumbs
    if ( $(".thumb a.thumbModal").length > 0 ) {
        $(".thumb a.thumbModal").imgPreview( { imgCSS:{width:"200px"} } );
    }
    if ( $(".thumb a.adModal").length > 0 ) {
        $(".thumb a.adModal").imgPreview( { imgCSS:{width:"200px"} } );
    }

    /* Note: this one is pretty crazy. Normally, the container for the preview
       image get created and attached to the DOM just above the closing </body>
       tag. If there's a modal window up though, that image will not be visible
       since it's obscured like everything else on the page when the modal window
       comes up. The solution is to move the image preview container, re-attaching
       it to something in the modal window. That's all fine, but then to positioning
       gets all screwy. That is the reason for the negative margins. They bring the
       image preview back to where we want it to be. */
    if ( $(".thumb a.adPopModal").length > 0 ) {
        $(".thumb a.adPopModal").imgPreview( { imgCSS:{width:"200px"}, onShow:function( hov ) {
            $(hov).append( this );
            $( this ).css( {marginTop:"-210px", marginLeft:"-720px"} );
        }} ).click( function( evt ) {  // kill the default action on click. We don't want to go anywhere.
            evt.preventDefault();
            return 0;
        } );
    }
    
    /* BEGIN Search stuff to do after DOM is ready */
    
    /* Browsers try to remember stuff, so when the DOM is ready:
     * 1. look for any div that are showing
     * 2. get their values
     * 3. show any divs that should appear b/c of an existing value
     */
    var divs = $("#searchForm div");
    var showBtnsFlag = false;
    $("#searchForm div").each( function( itm ) {
        if ( $(this).css( "display" ) == "block" ) {
            var val = $(this).children().children("select option:selected").val();
            if ( this.id == "searchByDiv" && val != "chooseSearchMethod" ) {
                $("#" + val).show();
                showBtnsFlag = true;
            } else if ( this.id == "artists") {
                $("#categories").show();
                showBtnsFlag = true;
            } else if ( this.id == "categories" && val == "paintings" ) {
                $("#mediumsDiv").show();
                showBtnsFlag = true;
            } else if ( this.id == "categories" && val == "sculpture" ) {
                $("#mediumsDiv").show();
            }
            // if calling show() on at least one div in going through this loop, then
            // also set the show btns flag
        }
    } );
    
    if ( showBtnsFlag ) {
        $("#searchBtns").show();
    }

    // Dynamically update the select options on the search page.
    $("#searchBy").change( function() {
        // remove any existing search by options
        $(".dynFormElement").hide();

        // show the correct set of choices based on current selection.
        var v = $("#" + this.id + " option:selected").val();
        $("#" + v ).show();

        // set selected to All Artists. This overrides the browsers tendency 
        // to save things, which is likely to be confusing for users and is 
        // definately a PITA to code.
        $("#" + v + " option:selected").attr( "selected", "");
        $("#" + v + " option:first").attr( "selected", "selected");
        // also show the buttons
        if ( v != "chooseSearchMethod" ) {
            $("#searchBtns").show();
        }
        
        // run the left column height method...
        setSidebarHt();
	} );

    // Assumed that the categories pulldown is already or will be populated 
    // via db query so all we have to do here is show it.
    $("#artist").change( function() {
        var v = $("#" + this.id + " option:selected").val();
        $("#categories").show();
        $("#categories option:selected").attr( "selected", "" );
        $("#categories option:first").attr( "selected", "selected" );
        $("#mediumsDiv").hide();
        $("#styles").hide();
    } );

    $("#categories").change( function()  {
        var v = $("#" + this.id + " option:selected").val();
        if ( v == "all" ) {
            $("#mediumsDiv").hide();
            $("#styles").hide();
        } else if ( v == "paintings" ) {
            $("#mediumsDiv").show();
            $("#mediums option:selected").attr( "selected", "" );
            $("#mediums option:first").attr( "selected", "selected" );
            $("#styles").hide();
        } else if ( v == "style" ) {
            $("#mediumsDiv").hide();
            $("#styles").show();
            $("#styles option:selected").attr( "selected", "" );
            $("#styles option:first").attr( "selected", "selected" );
        } else if ( v == "fineArtPrints" ) {
            $("#mediumsDiv").hide();
            $("#styles").show();
            $("#styles option:selected").attr( "selected", "" );
            $("#styles option:first").attr( "selected", "selected" );
        }
    } );
    
    //reset the <select> elements
    $('#searchReset').click( function() {
    } ); 
    /* END Search stuff to do after DOM is ready */

    // set up scrolling 
    $("div.scrollable").scrollable( {
        vertical:true,
        size:8
    } );
    $("div.nlScrollContainer").scrollable( {
        vertical:true,
        size:7
    } );

    // Do an AJAX submit for the newsletter signup form
    var nlOptions = { success:nlThankYou }; 
    var bnOptions = { success:bnThankYou }; 
    var contactOptions = { success:contactThankYou }; 
    // bind to the form's submit event 
    $('#newsletterSignupForm').submit( function() { 
        // inside event callbacks 'this' is the DOM element so we first 
        // wrap it in a jQuery object and then invoke ajaxSubmit 
        $(this).ajaxSubmit( nlOptions ); 
        // !!! Important !!! 
        // always return false to prevent standard browser submit and page navigation 
        return false; 
    } );
    $('#nighthorseForm').submit( function() {
        $(this).ajaxSubmit( bnOptions );
        return false; 
    } );
    $('#contactForm').submit( function() {
        $(this).ajaxSubmit( contactOptions );
        return false; 
    } );
} );

function nlThankYou() {
    $("#newsletterSignupForm").hide( 400 );
    $("#nlThankYou").show( 400 );
}

function bnThankYou() {
    $("#nighthorseForm").hide( 400 );
    $("#bnThankYou").show( 400 );
}

function contactThankYou() {
    $("#contactForm").hide( 400 );
    $("#contactThankYou").show( 400 );
}
