/**
 * Closet Couture JavaScript Functions
 * 
 * The most common JS functions used on CC. Mostly window element handling scripts.
 */

var siteurl = location.protocol+'\/\/'+location.hostname;

/*
Function: $get
This function provides access to the ÒgetÓ variable scope + the element anchor

Version: 1.3

Arguments:
key - string; optional; the parameter key to search for in the urlÕs query string (can also be Ò#Ó for the element anchor)
url - url; optional; the url to check for ÒkeyÓ in, location.href is default

Example:
>$get(ÓfooÓ,Óhttp://example.com/?foo=barÓ); //returns ÒbarÓ
>$get(ÓfooÓ); //returns the value of the ÒfooÓ variable if itÕs present in the current url(location.href)
>$get(Ó#Ó,Óhttp://example.com/#mooÓ); //returns ÒmooÓ
>$get(Ó#Ó); //returns the element anchor if any, but from the current url (location.href)
>$get(,Óhttp://example.com/?foo=bar&bar=fooÓ); //returns {foo:ÕbarÕ,bar:ÕfooÕ}
>$get(,Óhttp://example.com/?foo=bar&bar=foo#mooÓ); //returns {foo:ÕbarÕ,bar:ÕfooÕ,hash:ÕmooÕ}
>$get(); //returns same as above, but from the current url (location.href)
>$get(Ó?Ó); //returns the query string (without ? and element anchor) from the current url (location.href)

Returns:
Returns the value of the variable form the provided key, or an object with the current GET variables plus the element anchor (if any)
Returns ÒÓ if the variable is not present in the given query string

Credits:
Regex from [url=http://www.netlobo.com/url_query_string_javascript.html]http://www.netlobo.com/url_query_string_javascript.html[/url]
Function by Jens Anders Bakke, webfreak.no
*/
function $get(key,url){
    if(arguments.length < 2) url = location.href;
    if(arguments.length > 0 && key != ''){
        if(key == '#'){
            var regex = new RegExp('[#]([^$]*)');
        } else if(key == '?'){
            var regex = new RegExp('[?]([^#$]*)');
        } else {
            var regex = new RegExp('[?&]'+key+'=([^&#]*)');
        }

        var results = regex.exec(url);
        return (results == null )? '' : results[1];
    } else {
        url = url.split('?');
        var results = {};

        if(url.length > 1){
            url = url[1].split('#');
            if(url.length > 1) results["hash"] = url[1];
            url[0].split('&').each(function(item,index){
                item = item.split('=');
                results[item[0]] = item[1];
            });    
        }
        return results;
    }
}

/**
 * New Popup Window
 * 
 * Spawns a new window object and assigns a name to the window. If an existing window by the assigned name 
 * exists, it's brought to the front.
 * 
 * @param url full URL to load in the window
 * @param winname name of the window
 * @param width window dimension
 * @param height window dimension
 * @return
 */
var newWindow;

function makeNewWindow(url,winname,width,height) {
    if (!newWindow || newWindow.closed)
    {
        newWindow = window.open(url,winname,"status,width="+width+",height="+height+",scrollbars=yes,resizable=yes");
    }
    else
    {
        // window is already open, bring it to front
        newWindow.focus();
        if (newWindow.location != url) {
            newWindow.location = url;
        }
    }
}

/**
 * Closes the Standard Sized Windowlet
 * 
 * @return
 */
function closewin(md5) {
    var text = ''+parent.location+'';
    var pattern = /cat=([0-9]+|all)/;
    var result = text.match(pattern);
    if (result != null) {
        var cat = result[1];
    }
    
    var pattern = /st=([0-9]+)/;
    var result = text.match(pattern);
    if (result != null) {
        var st = result[1];
    }

    var pattern = /max_results=([0-9]+)/;
    var result = text.match(pattern);
    if (result != null) {
        var max = result[1];
    }
        
    if (cat) {
        if ($('closet')) {
            $('closet').set('load', {
                onComplete: function(e) { 
                    initPopups(); 
                }
            });
            $('closet').load('/more/?code=reload_closet&cat='+cat+'&max_results='+max+'&st='+st+'&md5check='+md5+'');
        }
    }
    
    if ($('popupWin')) {
        $('popupWin').empty().dispose();                            
    }
    else {
        window.close();
    }
}

/**
 * Enable New Custom Values for Select Lists
 * 
 * Apply to select lists where you want users to have the ability to select a "New" value and enter in a new value not shown 
 * as a select list option.
 * 
 * @param field_id the id value of the select element to process
 * @return
 */
function makeCustomSelects(field_id) {
    var block = {};
    var opt = {};
    var blockDiv = {};
    var blockField = {};
        
    if ($(''+field_id+'newblock')) {
        return;
    }
    blockDiv[field_id] = new Element('div');
    blockDiv[field_id].setProperty('id',field_id+'newblock');
    blockDiv[field_id].set('html','<strong>New Value:</strong>');

    blockField[field_id] = new Element('input');
    blockField[field_id].setProperties({'type':'text','id':'new'+field_id,'name':'new'+field_id,'class':'subfield','maxlength':'24'});
    blockField[field_id].injectInside(blockDiv[field_id]);
    blockDiv[field_id].injectAfter(field_id);   
    
    block[field_id] = new Fx.Slide(field_id+'newblock').hide();
    
    $(field_id).addEvent('change',function() {
        if (this.value == "new") {          
              block[field_id].slideIn();                    
              $('new'+field_id).focus();                      
        }
        else {
          block[field_id].slideOut();                   
        }
    }); 
    
    $('new'+field_id).addEvent('blur',function() { 
        block[field_id].slideOut(); 
        if (this.value !='') {
            opt[field_id] = new Element('option',{'value':this.value,'selected':true}).set('text',this.value).injectTop(field_id);
        }
    });
}

/**
 * Sets up a hideable sliding element
 * 
 * @param field_id
 * @return
 */
function setupSlideFx(field_id) {
    
    var slide = {};
    
    // The block to slide will be named after the field_id with a suffix of "-block"
    slide[field_id] = new Fx.Slide(field_id+'-block').hide();
    
    $(field_id).addEvent('click',function() {
        slide[field_id].toggle();
    });
}

/**
 * Build a Standard Sized Windowlet layered on top of active window
 * 
 * @return
 */
function makePopup(winClass) {

     if (!winClass) {
         winClass = 'popupWin';
     }
 
    if (!$('popupWin')) {
                
        var popup = new Element('div',{'id':'popupWin', 'class': winClass});
    
        popup.setStyles({
            'display':'none'
        });
        
        popup.inject('container','top');
    }   
    return $('popupWin');
}

/**
 * Build a small windowlet in the active window
 * 
 * @param message
 * @return
 */
function makeSmallPop(message) {

    if (!$('popupSmallWin')) {
        
        var popsmall = new Element('div',{'id':'popupSmallWin', 'class':'popupSmallWin', 'html':message});
        var mask = new Element('div',{'id':'mask','class':'mask'});
        
        popsmall.injectAfter('container');
        mask.injectBefore('container');
    }   
}

/**
 * Prefilled Forms Shadow Text
 * 
 * Allows for input form fields to be prefilled, but blanked out the first time they are entered.
 * 
 * @return
 */
function shadowtext() {
        this.value = '';
        this.removeClass('shadowtext');
        this.removeEvent('focus',shadowtext);           
}

/**
 * Approval Dialog Box
 * 
 * Reads text stored in the title property of the passed element and uses it as an approval message. 
 * User confirms or cancels action. If user confirms, the passed URL is loaded. 
 * 
 * @param updateElm
 * @return
 */
function confirmationPrompts(updateElm, title) {

    $$('.confirm').addEvent('click',function(e){
        e.stop();

        if (this.type == 'button') {
            var url = this.alt;         
        }
        else {
            var url = this.href;
        }
        makeSmallPop();
        
        if (!title) {
            title = this.title;
        }
        var message = "<h3>Please Confirm This Action</h3><p>"+title+"</p><div style=\"text-align:center;\"><input type=\"button\" id=\"cancel\" value=\"Cancel\"> &nbsp; <input type=\"button\" id=\"confirm\" value=\"Continue\"></div>";

        $('popupSmallWin').set('html',message);
        $('popupSmallWin').setStyle('zIndex',8000);
        $('mask').setStyle('zIndex',7900);
        
        $('cancel').addEvent('click',function(){
            $('popupSmallWin').dispose();
            $('mask').dispose();
            title='';
        });
        
        $('confirm').addEvent('click',function(){
            if (updateElm) {
                var confAjax = new Request.HTML({
                    url: url,
                    update: updateElm,
                    onSuccess: function() {
                        confirmationPrompts(updateElm);     
                        $$('.hover').addEvent('click',function(e){
                            e.stop();
                            var string = "?";
                            var url = this.href;
                            if (url.indexOf(string) == -1) {
                                url += "?hover=1";
                            }
                            else {
                                url += "&hover=1";
                            }
                            
                            confAjax.get(url);
                        });                         
                    }
                }).get();
                $('popupSmallWin').dispose();
                $('mask').dispose();   
                title = '';
            }
            else {
                window.location = url;
            }
        });                 
    });
}

/**
 * Confirmation Dialog Box
 * 
 * @param message text message to show user 
 * @return
 */
function acknowledge(message, title) {
                    
        makeSmallPop();
        if (!title) {
            title = "Update Message";
        }
        var message = "<p style=\"padding: 0px; 10px;\"><h3 style=\"margin-bottom:10px;\">"+title+":</h3>"+message+"</p><div style=\"text-align:center; margin-top:20px;\"><input type=\"button\" id=\"ok\" value=\"OK\"></div>";
        $('popupSmallWin').set('html',message);

        $('ok').addEvent('click',function(){
            $('popupSmallWin').dispose();
            $('mask').dispose();
        });     
}

/**
 * Initialize AJAX Request Calls and Layered Window Boxes
 * 
 * Called on docready on most pages of CC
 * 
 * @return
 */
function initPopups() {
     var SubmitForm = new Request ({
                     useWaiter: true,
                     method: 'post',
                     waiterOptions: {
                         fxOptions: {duration: 500, baseHref:siteurl+'/images/spinner.gif'}
                     },
                     url: siteurl,
                     onSuccess: 
                         function(e) {
                             $('popupWin').set('html',''+this.response.text+'');
                             initPopups();
                         }
                     });


    var Ajax =  new Request({
                    evalScripts: true,
                    async: false,
                    useWaiter: true,
                    waiterOptions: {
                        fxOptions: {duration: 500}
                    },                  
                    onSuccess: function() {                        
                        $('popupWin').set('html',''+this.response.text+'');
                        $('popupWin').setStyle('display','block');
                        $('popupWin').makeDraggable({'handle': $$('.header')});
                        $$('#popupWin .hover').addEvent('click',function(e){
                            e.stop();

                            makePopup(this.title);
                            
                            $$('.tips').destroy();
                            var string = "?";
                            var url = this.href;
                            if (url.indexOf(string) == -1) {
                                url += "?hover=1";
                            }
                            else {
                                url += "&hover=1";
                            }
                            Ajax.get(url);
                        });

                        confirmationPrompts('popupWin');
                        
                        //Build custom selector options for drop down lists
                        $$('.customselect').each(function(el){
                            makeCustomSelects(el.id);
                        });

                        // Setup sliding divs
                        $$('.slide').each(function(el){
                            setupSlideFx(el.id);
                        });
                                                
                        // Setup any date pickers
                        if ($('date') && !$$('.calendar')) {
                            myCal = new Calendar({ 'date': 'm/d/Y' }, { 'direction': 0, 'navigation': 1, 'tweak': { 'x': 10, 'y': -50 }});
                        }
        
                        // Make tooltips if needed
                        var toolTips = new Tips('.texttip', { 'className': 'tips', 'hideDelay': 0, 'showDelay': 100, 'offsets': {'x':10,'y':10} });
                        
                        $$('.texttip').addEvent('click',function(e){
                            toolTips.hide();
                        });
                        
                        if ($('popupWin').getElement('.infobox')) {
                            $('pophelpbutton').setStyle('display','block');
                            $('pophelpbutton').addEvent('mouseover',function(e) {
                                $$('#popupWin .infobox').setStyle('display','block');
                                
                                $$('#popupWin .infobox').fade(.98);
                            });
                                        
                            $('pophelpbutton').addEvent('mouseleave',function(e) {
                                $$('#popupWin .infobox').fade(0);
                            });
                        }
                            
                        if ($$('.shadowtext')) {
                            $$('.shadowtext').addEvent('focus',shadowtext);
                        }                       
                             
                        if ($('updateform')) {                            
                            $('updateform').addEvent('submit', function(f) {                             
                                f.stop();                             
                                SubmitForm.post($('updateform'));
                            });                     
                        }    
                    }
                });
    
                $$('.hover').addEvent('click',function(e){
                    e.stop();
                    makePopup(this.title);
                    var string = "?";
                    var url = this.href;
                    if (url.indexOf(string) == -1) {
                        url += "?hover=1";
                    }
                    else {
                        url += "&hover=1";
                    }
                    
                    Ajax.get(url);
                });

                $$('.guide').addEvent('click',function(e){
                    e.stop();
                    makePopup('codebox');
                    var string = "?";
                    var url = this.href;
                    Ajax.get(url);
                    $('codebox').setStyle('display','block');
                    $('codebox').fade('show');
                    $('codebox').makeDraggable();
                    
                    if ($$('.closeguide')) {
                        $$('.closeguide').addEvent('mousedown',function(evt) {
                            $$('.codebox').dispose();   
                        });
                    }
                });                
                confirmationPrompts();
    
                $$('.acknowledge').addEvent('click',function(e){
                    e.stop();

                    if (this.type == 'button') {
                    var url = this.alt;         
                }
                else {
                    var url = this.href;
                }
                        
                makeSmallPop();

                var message = "<p>"+this.title+"</p><div style=\"text-align:center;\"><input type=\"button\" id=\"ok\" value=\"OK\"></div>";
                $('popupSmallWin').set('html',message);
        
                $('ok').addEvent('click',function(){
                    $('popupSmallWin').dispose();
                    $('mask').dispose();
                });     
            });     
        
            if ($('container')) {   
                if ($('container').getElement('#guidebox')) {
                    $('guidebox').makeDraggable();          
                    
                    if ($('hide_form')) {
                            $('hide_guide').addEvent('mousedown',function(e) {
                            $('hide_form').send();
                        });
                    }
                    
                    document.addEvent('keydown',function(evt) {
                        if (evt.key=="esc") {
                            $('guidebox').fade(0);
                            $('guidebox').dispose();                        }
                    });         
                    
                    $$('.closeguide').addEvent('mousedown',function(evt) {
                        $('guidebox').fade(0);   
                        $('guidebox').dispose();
                    });
                    initGuide();
                }
            }
    
        // Make tooltips if needed
        var texlTips = new Tips('.texttip', { 'className': 'tips', 'hideDelay': 0, 'showDelay': 100, 'offsets': {'x':10,'y':10} });
        var toolTips = new Tips('.tooltip', { 'className': 'tooltips', 'hideDelay': 0, 'showDelay': 100, 'offsets': {'x':10,'y':10} });
            
        if ($$('.shadowtext')) {
            $$('.shadowtext').addEvent('focus',shadowtext);
        }       
        
        $$('.follow').addEvent('mousedown',function(e){
            e.stop();
            
            var follow = this;
            new Request.JSON({
                link:'chain',
                onComplete: function(action) { 
                    var result = action;
                    follow.href = result.url;

                    var img 	= follow.getFirst('img');
                    img.src 	= result.image;    
                	img.title 	= result.title;
                }
            }).get(this.href);      
            _gaq.push(['_trackEvent', 'follow_user', this.href]); 
        });
}
 
function loadGuide(guideName) {
	new Request ({
        useWaiter: true,
        waiterOptions: {
            fxOptions: {duration: 500, baseHref:siteurl+'/images/spinner.gif'}
        },
        evalScripts: true,
        onComplete: 
            function(e) {
        		var guidebox = new Element('div', {'html':this.response.text});
        		guidebox.inject('container');
        		
        		$('guidebox').setStyles({'opacity':'0', 'display':'block'});
        		$('guidebox').makeDraggable();          
        		
        	    if ($('hide_form')) {
                    $('hide_guide').addEvent('mousedown',function(e) {
                    	$('hide_form').send();
                    });
        	    }
            
        	    document.addEvent('keydown',function(evt) {
        	    	if (evt.key=="esc") {
        	    		$('guidebox').fade(0);
            	    	$('guidebox').dispose();
        	    	}
        	    });         
            
        	    $$('.closeguide').addEvent('mousedown',function(evt) {
        	    	$('guidebox').fade(0);   
        	    	$('guidebox').dispose();
        	    });            	    

        		initGuide();        		
            }
        }).get(siteurl+'/guide/'+guideName+'/');
}
 
 
function initGuide() {
    var helpblock = new Fx.Tween('content');

    $$('#help_content a').each(function(e) {
        if (e.getProperty('class')) {
            return;
        }

        e.addEvent('click',function(evt) {
            evt.stop();         
            helpblock.start('opacity','0').chain(function() {
                $('help_content').set({method:'get', evalScripts:false});
                $('help_content').load(e.href);
                helpblock.start('opacity','1');
            }).chain(function() {
                initGuide();
            });
        });
    });

    if ($('guide_form')) {
        $$('#submit_guide_form').addEvent('click',function(event) { 
            new Request.HTML({
                url: $('guide_form').action,
                update: $('content'),
                data: $('guide_form'),
                onComplete: function(e) {
                    initGuide();                    
                },
                useWaiter: true,
                waiterOptions: {
                    fxOptions: {duration: 500}
                }
                }).post($('guide_form'));
        });
    }
}

function reloadClosetNav() {

    var closetNav = new Fx.Tween('closetnav');

    closetNav.start('opacity','0').chain(function() {
        $('closetnav').load(siteurl+'/more/?code=closetnav');
        closetNav.start('opacity','1');
    });
}

function loadFieldValue(fieldName, getUrl) {
    new Request.HTML({
        url: getUrl,
        onComplete: function(e) {
            $(''+fieldName+'').value = this.response.text;
        }
    }).get();
}

/* A workaround for IE issues in mootools 1.2.1
 * - Recreates FX.Scroll() but utilises 1.2.0's getPosition/getOffset routines.
 */
Fx.Scroll = new Class({
 
    'Extends': Fx.Scroll,
 
    'styleString': Element.getComputedStyle,
    'styleNumber': function(element, style) {
        return this.styleString(element, style).toInt() || 0;
    },
    'borderBox': function(element) {
        return this.styleString(element, '-moz-box-sizing') == 'border-box';
    },
    'topBorder': function(element) {
        return this.styleNumber(element, 'border-top-width');
    },
    'leftBorder': function(element) {
        return this.styleNumber(element, 'border-left-width');
    },
    'isBody': function(element) {
        return (/^(?:body|html)$/i).test(element.tagName);
    }, 
    'toElement': function(el) {
        var offset   = {x: 0, y: 0};
        var element  = $(el);
       
        if (this.isBody(element)) {
            return offset;
        }
        var scroll = element.getScrolls();
               
        while (element && !this.isBody(element)){
            offset.x += element.offsetLeft;
            offset.y += element.offsetTop;
           
            if (Browser.Engine.gecko){
                if (!this.borderBox(element)){
                    offset.x += this.leftBorder(element);
                    offset.y += this.topBorder(element);
                }
                var parent = element.parentNode;
                if (parent && this.styleString(parent, 'overflow') != 'visible'){
                    offset.x += this.leftBorder(parent);
                    offset.y += this.topBorder(parent);
                }
            } else if (Browser.Engine.trident || Browser.Engine.webkit){
                offset.x += this.leftBorder(element);
                offset.y += this.topBorder(element);
            }
 
            element = element.offsetParent;
            if (Browser.Engine.trident) {
                while (element && !element.currentStyle.hasLayout) {
                    element = element.offsetParent;
                }
            }
        }
        if (Browser.Engine.gecko && !this.borderBox(element)){
            offset.x -= this.leftBorder(element);
            offset.y -= this.topBorder(element);
        }
       
        var relative = this.element;
        var relativePosition = (relative && (relative = $(relative))) ? relative.getPosition() : {x: 0, y: 0};
        var position = {x: offset.x - scroll.x, y: offset.y - scroll.y};
       
        return this.start(position.x - relativePosition.x, position.y - relativePosition.y);
    }
});
 