// Common utility actions, in a nice namespace. 
// Goal is browser support for IE6+, FF2+, Safari and Opera
Riven = {
    // Cross-browser object getter, by ID
    get: function(name) {  
        if (document.getElementById) {  
            return document.getElementById(name);

        } else if (document.all) {
            return document.all[name];

        } else if (document.layers) {
            return document.layers[name];
        }
        return(null);
    },

    // Show/hide based on current visibility
    toggle: function(id) {
        var el = Riven.get(id);    
        var visible = el.style.display != 'none';    
        el.style.display = (visible) ? 'none' : '';    
        return(!visible);
    },

    // Sets an element's visibility by ID, or shows by default
    show: function(id, visible) {
        if (visible == null) {visible = true;}
        var el = Riven.get(id);
        if (el) {el.style.display = (visible) ? '' : 'none';}
    },
    
    // Hides an element by ID
    hide: function(id) {
        Riven.show(id,false);
    },

    // Set focus to a control
    setFocus: function(id) {
        var item = Riven.get(id);
        if (item) {item.focus();}
    },

    // Enable
    enable: function(id, enabled) {
        if (enabled == null) {enabled = true;}
        var el = Riven.get(id);
        if (el) {el.disabled = !enabled;}
        return enabled;
    },

    // Disable
    disable: function(id) {
        return Riven.enable(id, false);
    },

    // Set CSS class
    setClass: function(id, klass) {
        var item = Riven.get(id);
        if (item) {
            item.setAttribute("class", klass);
            item.setAttribute("className", klass);
        }
    },

    // Update the contents of the given element
    updateEl: function(id, text) {
        var el = Riven.get(id);
        if (el) { el.innerHTML = text; }
    },

    // Gets the specified element's position on the page, as [x,y] array.  [0,0] if error or unsupported.
    getPos: function(id) {
        var curleft = 0;
        var curtop = 0;
        var el = Riven.get(id);
        if (el && el.offsetParent) {
            do {
                curleft += el.offsetLeft;
                curtop += el.offsetTop;
            } while (el = el.offsetParent);
        }
        return [curleft,curtop];
    },

    // Add a rollover on the given element for the given image.  If no srcOver is
    // specified, defaults to adding "-over" to src's filename.  There is
    // no need to specify /res/ at the start of the src and srcOver params.
    installRollover: function(id, imgId, src, srcOver) {
        if (imgId == null) {imgId = id;}
        var el = Riven.get(id);
        if (el) {
            var srcUrl = src;
            if (!srcUrl.match(/^\/?res\//)) {
                srcUrl = '/res/'+srcUrl;
            }
            var srcOverUrl = srcUrl.replace(/(\.[a-zA-Z]+)$/,'-over$1');
            if (srcOver) {
                srcOverUrl = srcOver;
                if (!srcOverUrl.match(/^\/?res\//)) {
                    srcOverUrl = '/res/'+srcOverUrl;
                }
            }
            el.onmouseover = function() {Riven.get(imgId).src = srcOverUrl;};
            el.onmouseout = function() {Riven.get(imgId).src = srcUrl;};
        }
    },

    // Filters a select input element's states based on a select with
    // national markets listed - used in CRM for market editing.
    // Pass in id's for national and state select elements as params.
    filterStates: function(nationID, stateID) {
        var nations = $('#'+nationID);
        var states = $('#'+stateID);
        var cache = $('#'+stateID+'-cache');
        
        // Sanity check
        if (!nations || !states) {
            return;
        }

        var curNation = nations.val();
        if (!this.curNation || curNation != this.curNation) {
            // Save our current val, and clear out the states select
            this.curNation = curNation;
            states.empty();

            if (curNation) {
                // Clone all options that have their national market id set to our current selection into the states control
                var selID = cache.val().match(/[^\-]+$/);
                cache.find("option[national_market_id='"+curNation+"']").clone().appendTo(states);
                states.find("option").each(function() {
                    // Set option vals to correct value (strip national id)
                    $(this).attr('value',$(this).attr('value').match(/[^\-]+$/));
                });
                states.show();
                states.val(selID);
                $('#'+stateID+'-none').hide();
            } else {
                // No selected nation, so reset value and hide it
                states.hide();
                $('#'+stateID+'-none').show();
            }
        }
        
    },

    filterCities: function(mode) {
        // If mode is not set, do both modes
        if (mode == null) {
            Riven.filterCities('quicksearch');
            Riven.filterCities('body');
            return;
        }

        // Get our nodes
        var states = $('#'+mode+'-state');
        if (!states || states.length == 0) { return; }
        var cities = $('#'+mode+'-city');
        var cache = $('#'+mode+'-city-cache');
        var curCity = cities.val();

        // Ensure the cache is populated
        if (cache.find('option').length <= 0) {
            cities.find('option').appendTo(cache);
        }

        // Populate the main select with the appropriate items
        var curState = states.val();
        if (!this.curState || curState != this.curState[mode]) {
            // Save our current val, and clear out the cities select
            if (!this.curState) { this.curState = []; }
            this.curState[mode] = curState;
            cities.empty();

            if (curState.length > 0) {
                // Clone first option ("any") and all options that have the state attribute set to our state abbreviation
                cache.find("option:first, option[state='"+curState+"']").clone().appendTo(cities);
                if (curCity && curCity != '') {cities.val(curCity);}
                $('#'+mode+'-city-row').show();
            } else {
                // No selected state, so reset city value and hide it
                $('#'+mode+'-city-row').hide();
            }
        }
    },

    // Called once on page load
    onPageLoad: function() {
        // Update visibility of elements based on javascript availability
        $('.js-hide').hide();
        $('.js-show').show();

        // IE hack to get mouseover look for our buttons
        $('button').hover(
            function() {$(this).addClass('iehover');},
            function() {$(this).removeClass('iehover');}
        );

        // Layout specific items
        Riven.filterCities();
    }

};

////////////////////////////////////////////////////
// Ajax helper class - very simple, but does the job
////////////////////////////////////////////////////
Riven.Ajax = function() {
    // Constructor
    this.xmlhttp = null;
    if (window.XMLHttpRequest) {
        // Mozilla/Safari/Non-IE
        this.xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        // IE
        this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
};

// Spec out members
Riven.Ajax.prototype = {

    // Call to query, with result entered into given element
    update: function(id,queryUrl,loadingText) {
        var ok = this.query(queryUrl, function(ajax, text) {
            // Set contents of element on success
            Riven.updateEl(id,text);
        });
        // Handle loading status
        if (ok && loadingText && loadingText.length > 0) {
            if (loadingText == null) {
                loadingText = '<span style="color:#aaa;background: transparent url(/res/loading.gif) no-repeat;padding-left:20px;line-height:16px;">Loading...</span>';
            }
            Riven.updateEl(id,loadingText);
            Riven.show(id);
        }
    },

    // Generic ajax query, calls callback on success
    query: function(url, callback, scope) {
        // Verify we have an xmlhttp object
        var owner = this;
        var req = this.xmlhttp;
        if (!req) {return false;}

        // Set up query
        req.open('GET', url);
        
        // Set result handler
        req.onreadystatechange = function() {
            if (req.readyState == 4 /*status complete*/) {
                if (req.status == 200 /* HTTP OK */) {
                    // Call our update handler with response text
                    callback.call(scope||this, owner, req.responseText);
                }
            }
        };

        // Start the query
        req.send(null);
        return true;
    }
};

function AddToMylist(returnPage) {
	var str = '';
	
	for (var i=0;i< document.results.elements.length;i++) {
    if (document.results.elements[i].name == 'listing_ids[]') {
    	if (document.results.elements[i].checked == true) {
	    	if (str != '') { str = str + ','; }
	      str = str + document.results.elements[i].value;
	    }
  	}
  }
  
  top.location.href = './index.php?module=mylist&page=add_listings&listing_ids=' + str + '&clause=' + returnPage;
};

function resetQuickSearch(){
	var f = document.QuickSearch;
	for (var i=0;i<f.elements.length; i++ ){
		if (f.elements[i].type == 'select-one'){
			f.elements[i].selectedIndex=0;
		}
	}
};

function changeImages(id, src) { 
	  var el = Riven.get(id);
	  if (el) { el.src = src; }
};

// Sets up any global page js stuff needed
$(document).ready(function() {Riven.onPageLoad();});
