if (typeof console == "undefined") { var console = {log:function(dummy){}}; }

/**
* Functions for controlling the suggestion stuff
*/
var didyoumean_states={};
function switch_didyoumean(element_id) {
    if (didyoumean_states[element_id]==undefined || didyoumean_states[element_id]=='short') {
        $("#short_"+element_id).css({display:'none'});
        $("#extended_"+element_id).css({display:'inline'});
        didyoumean_states[element_id]='extended';
        $("#"+element_id+"_switch").text("less...");
    } else if (didyoumean_states[element_id]=='extended') {
        $("#short_"+element_id).css({display:'inline'});
        $("#extended_"+element_id).css({display:'none'});
        didyoumean_states[element_id]='short';
        $("#"+element_id+"_switch").text("more...");
    }
}
/**
 * Functions that control the styles of the header tabs and the value of the what_who_input field
 */
var tabs={
    selected:false,
    lasttab:false,
    over:function (element) {element.className = 'overTab javaTab';},
    out:function (element) {if (element!=tabs.selected) {element.className = 'offTab javaTab';}},
    click:function (element,action) {tabs.selected=element;action(element);}
};

function click_who(element) {
    $('#what_tab').removeClass().addClass('offTab javaTab');
    element.className = 'overTab javaTab';
    $('#what_who_input').attr('value', "who");
    $('#search_details_what').hide();
    $('#search_details_who').css({display:"inline"});
    $('#header_search').attr('action', $('#action_who').attr('value'));
    $('#searchwhat').attr('name', 'name');
    var whoVal =  get_cookie('saved_input_name');
    $('#searchwhat').text((whoVal)? whoVal : "");
}

function click_what(element){
    $('#searchwhat').focus();
    element.className = 'overTab javaTab';
    $('#who_tab').removeClass().addClass('offTab javaTab');
    $('#what_who_input').text("what");
    $('#search_details_what').css({display:"inline"});
    $('#search_details_who').hide();
    $('#header_search').attr('action', $('#action_what').attr('value'));
    $('#searchwhat').attr('name', 'searchwhat');
    var whatVal = get_cookie('saved_input_searchwhat');
    $('#searchwhat').text((whatVal)? whatVal : ""); 
}

/* FILE: cookies.js */

// The Domain must be declared for cookies to work
// The spec for cookies, an rfc older than the hills, calls for 2 dots
var domain = ".n49.ca";

/* Function: This function loading in a cookie from the uses system */
function get_cookie(cookie_name) {
    var results = document.cookie.match (cookie_name + '=(.*?)(;|$)');
    if (results){return(unescape(results[1]));}
    else{return null;}
}

/* Function: This function sets a cookie to the uses system */
function set_cookie(name, value, expires){

    var cookie_string = name + "=" + escape(value);

    var today = new Date();
    today.setTime(today.getTime());
    if (!expires){    var expires = 365;   }
    expires = expires * 60 * 60 * 24 * 1000;

    var expires_date = new Date( today.getTime() + (expires) );
    cookie_string += "; expires=" + expires_date.toGMTString();

    cookie_string += "; path="+ '/';
    cookie_string += "; domain=" + domain;

    document.cookie = cookie_string;

}

function delete_cookie(cookie_name){
    var cookie_date = new Date ();  // current date & time
    cookie_date.setTime (cookie_date.getTime() - 1);
    document.cookie = cookie_name + "=; expires=Thu, 01-Jan-1970 00:00:01 GMT";
    return false;
}

function setMail(id, name, gloablDomain, domainName, changeHTML) {  // Kind of obfuscates an email...mostly.
    var aTag = document.getElementById(id);
    var emAd = name+"@"+domainName+"."+gloablDomain
    aTag.innerHTML = (changeHTML) ? changeHTML : emAd; 
    aTag.href = "mailto:"+emAd;
    return false;
}
 
/**
 * This will take the data from a JSON response and place it into a specified DIV
 * @params {object} $data array returned from the call [elementID, html]
 */
function callback_populateContent($data){
    if(!$data)       {  error_handler_by_id('No data, probably an error in the Json file.'); return false;   }
    ($data.err_code) ?  error_handler_by_id($data.err_code) : $("#"+$data.elementID).html($data.html);
}

var loaded_scripts=[];
/**
 * This function loads in a js file and adds to to be DOM
 * @params {string} $sourse Location of new JS file
 */
function loadScript($source) {
    if (!loaded_scripts[$source]) {
        loaded_scripts[$source]=true;
        newScript = document.createElement('script');
        newScript.src = $source;
        document.body.appendChild(newScript);
    }
    return false;
}

/**
 * All Pop Calls should be ported through this function
 * @param string $type Indicating the type of popup content
 * @param array $additionalParams These will be passed into the AJAX call and also contain the H1 of the popup  
 */
var popup={
    login:function() {
        loadScript('/js/content_display/login.js');
        this.display('circle', 'login', 'LOGIN');
    },
    forgot_password:function() {
        this.display('circle', 'forgot_password', 'FORGOT PASSWORD?');
    },
    tags_what:function() {
        this.display('circle', 'tags_what', 'WHAT ARE TAGS?');
    },
    tags_why:function() {
        this.display('circle', 'tags_why', 'WHY USE TAGS?');
    },
    tags_edit:function($additionalParams) {
        this.display('circle', 'tags_edit', 'EDIT TAGS', $additionalParams );
    },
    image_enlarge:function($additionalParams) {
        loadScript('/js/content_display/images.js');
        this.display('square', 'image_enlarge', 'IMAGE GALLERY', $additionalParams, callback_image_enlarge);
    },
    image_enlarge_switch:function($additionalParams) {
        var json = new JSON;
        var params = {
            "element_id":'popup_content_square_popup_'+popupIds,
            "request_type":"image_enlarge",
            "h1":"Image Enlarge",
            "popup_type":"square"
        }
        inlinePopups[params.element_id] = false;
        // Only attaching the Extra Params If the $additionalParams is set as an array
        if(typeof $additionalParams == 'object'){ params.additional = $additionalParams; }
        var json = new JSON;
        json.async = false;
        json.request('popup_content',params,function($data){$('#popup_content_square_popup_'+(popupIds-1)).html($data.html);},'','/libs/JSON/misc_actions.php');
    },
    video_enlarge:function($additionalParams) {
        loadScript('/js/content_display/videos.js');
        this.display('square', 'video_enlarge', 'VIDEO GALLERY', $additionalParams, callback_video_enlarge);
    },
    quick_quote:function($additionalParams) {
        loadScript('/js/content_display/quick_quote.js');
        this.display('square', 'quick_quote', 'QUICK QUOTE', $additionalParams);
    },
    email_business:function($additionalParams) {
        loadScript('/js/content_display/email_business.js');
        this.display('square', 'email_business', 'EMAIL A BUSINESS', $additionalParams);
    },
    add_image:function($additionalParams) {
        if($('#add_image_form_'+$additionalParams[1])[0]){
            if($section_type == 'listing_details'){
                if($('#images_content').is(":hidden")){
                    change_tabs($('#images')[0]);
                    $('#images').click();
                }
            }
            window.location.href = '#add_image_form_'+$additionalParams[1]+'_a';
        }else{
            loadScript('/js/content_display/images.js');
            this.display('square', 'add_image', 'ADD AN IMAGE', $additionalParams);
        }
    },
    add_video:function($additionalParams) {
        if($('#add_video_form_'+$additionalParams[1])[0]){
            if($section_type == 'listing_details'){
                if($('#videos_content').is(":hidden")){
                    change_tabs($('#videos')[0]);
                    $('#videos').click();
                }
            }
            window.location.href = '#add_video_form_'+$additionalParams[1]+'_a';
        }else{
            loadScript('/js/content_display/videos.js');
            this.display('square', 'add_video', 'ADD A VIDEO', $additionalParams, callback_add_video);
        }
    },
    add_review:function($additionalParams) {
        if($('#review_buisness_form_'+$additionalParams[1])[0]){
            if($section_type == 'listing_details'){
                if($('#reviews_content').is(":hidden")){
                    change_tabs($('#reviews')[0]);
                    $('#reviews').click();
                }
            }
            window.location.href = '#review_buisness_form_'+$additionalParams[1]+'_a';
        }else{
            loadScript('/js/content_display/add_review.js');
            loadScript('/js/content_display/reviews.js');
            this.display('square', 'add_review', 'REVIEW THIS BUSINESS', $additionalParams, callback_reviewBusinessDisplay);
        }
    },
    review_comment:function($additionalParams) {
        loadScript('/js/content_display/reviews.js');
        this.display('square', 'review_comment', 'COMMENT ON THIS REVIEW', $additionalParams);
    },
    article_comment:function($additionalParams) {
        loadScript('/js/content_display/articles.js');
        this.display('square', 'article_comment', 'COMMENT ON THIS ARTICLE', $additionalParams);
    },
    attach_article:function($additionalParams) {
        loadScript('/js/content_display/articles.js');
        this.display('square', 'attach_article', 'ATTACH THIS ARTICLE', $additionalParams);
    },
    lead_comment:function($additionalParams) {
        loadScript('/js/content_display/leads.js');
        this.display('square', 'lead_comment', 'EDIT COMMENT', $additionalParams);
    },
    edit_elt_txt:function ($additionalParams) {
        loadScript('/js/content_display/edit_caption.js');
        this.display('square', 'edit_elt_txt', 'EDIT CAPTION', $additionalParams);
    },
    email_friend:function ($additionalParams) {
        loadScript('/js/content_display/email_friend.js');
        this.display('square', 'email_friend', 'EMAIL TO FRIEND', $additionalParams);
    },
    add_favourites:function ($additionalParams) {
        this.display('circle', 'add_favourites', 'ADD TO FAVOURITES', $additionalParams);
    },
    add_friend:function ($additionalParams) {
        loadScript('/js/content_display/members.js');
        this.display('square', 'add_friend', 'ADD A FRIEND', $additionalParams);
    },
    inappropriate:function ($additionalParams) {
        loadScript('/js/content_display/inappropriate.js');
        this.display('square', 'inappropriate', 'INAPPROPRIATE?', $additionalParams);
    },
    directory_browser:function ($additionalParams) {
        loadScript('/js/content_display/directory_browser.js');
        this.display('square', 'directory_browser', 'FIND A BUSINESS');
    },
    what_is_public_private:function ($additionalParams) {
        this.display('circle', 'what_is_public_private', 'WHAT ARE THESE?', $additionalParams);
    },
    report_bug:function ($additionalParams) {
        if( $additionalParams[0] == 'Link from footer' || $additionalParams['force_display']) {
            if($('#bug')[0]){
                $('#bug').attr('value', $('#bug').attr('value')+" <hr /> "+$additionalParams[0]);
                $('#bug_error_display').html($('#bug_error_display').html()+"<hr />"+$additionalParams[0]);
            }else{
                $additionalParams[0] = "URL: "+window.location+" <hr /> Browser: "+navigator.userAgent+" <hr /> "+$additionalParams[0];
                loadScript('/js/content_display/report_bug.js');
                this.display('square', 'report_bug', 'REPORT A BUG', $additionalParams);
            }
        } else {
            // Bugs are automatically submitted
            var params = new Array();
            params[0] = window.location.href;
            params[1] = navigator.userAgent;
            params[2] = navigator.platform;
            params[3] = $additionalParams[0];
            var json = new JSON;
            json.request('report_bug',params,callback_report_bug,'','/libs/JSON/misc_actions.php') ;
        }
    },
    feedback:function ($additionalParams) {
        loadScript('/js/content_display/feedback.js');
        this.display('square', 'feedback', 'FEEDBACK', $additionalParams);
    },
    delete_business:function ($additionalParams) {
    	loadScript('/js/content_display/delete_business.js');
        this.display('square', 'delete_business', 'DELETE BUSINESS', $additionalParams);
    },
    copy_image:function ($additionalParams) {
        this.display('square', 'copy_image', 'COPY IMAGE', $additionalParams);
    },
    send_sms:function ($additionalParams) {
        this.display('square', 'send_sms', 'SEND TO PHONE', $additionalParams);
    },
    choose_image:function($additionalParams) {
        this.display('square', 'choose_image', 'CHOOSE AN IMAGE', $additionalParams);
    },
    choose_video:function($additionalParams) {
        this.display('square', 'choose_video', 'CHOOSE A VIDEO', $additionalParams);
    },
    fade_out:function() {
        if(document.body.firstChild.id != 'popupWrapper'){
            // Making the height of the white out the same as the height of the wrapper
            $('#fadeOver').height($(document).height());

            // Calling the Appear for the fadeOver image
            
            $('#fadeOver').css({display:"block", opacity:0})
            $('#fadeOver').fadeTo("fast", 0.5);
            $('#fadeOver').dblclick(popup_close_all);
            popupWrapper = document.createElement('div');
            popupWrapper.className = 'popup_wrapper';
            popupWrapper.id = 'popupWrapper';
            document.body.insertBefore(popupWrapper, document.body.firstChild);
        } else {
            $("#popupWrapper").fadeIn();
            $("#fadeOver").fadeIn();
        }
    },
    /**
     * Sets up the container for diplay and calls for the content using AJAX and JSON 
     *
     * @param string $popupType Indicating the type of popup element(circle, square)
     * @param array $contentType Sent as params['request_type'] to indicate the type of popup content
     * @param string $h1_str The H1 to display in the popup
     * @param array $additionalParams These are passed into the AJAX call as params['additional'] 
     * @param function customCallBack Is sent in if the AJAX call needs a differnt callBack then callback_popupContentDisplay
     */
    display:function ($popupType, $contentType, $h1_str, $additionalParams, customCallBack) {
        // Bringing In The White Out If There Is No Popup Already
        popup.fade_out();

        // Creating a new name for this DIV Popup
        var thisElementID = $popupType+'_popup_'+popupIds;
        popupIds ++;

        // Creaing a virtual DIV to set
        var newPopup = document.createElement('div');
        newPopup.className = 'popup_element';
        newPopup.id = thisElementID;
        
        if($popupType == 'circle'){
            var thisElementClass = 'circle_element';
        }else{
            var thisElementClass = 'square_element';
        }

        // Setting up the base Div HTML Structure
        var thisElementContent = '<table style="width: 100%;"><tr><td style="width:33%"></td><td style="width:33%" align="center">';
        thisElementContent += '<div id="popup_element_'+thisElementID+'" class="'+thisElementClass+'" style="visibility:hidden; position:relative; text-align:left;">';
        thisElementContent += '    <div id="popup_h1_'+thisElementID+'">';
        thisElementContent += '        <div class=\'h1\'>';
        thisElementContent += '            <h1><div id="popup_h1_flash_'+thisElementID+'">'+$h1_str+'</div></h1>';
        thisElementContent += '        </div>';
        thisElementContent += '    </div>';    
        thisElementContent += '    <div class="contentHolder"><div id="popup_content_'+thisElementID+'" class="innerContentHolder"></div></div>';
        thisElementContent += '    <div class="closeButton button redText" onClick="popup_close_all();">close</div>';
        thisElementContent += '</div></td><td style="width: 33%"></td></tr></table>';

        // Writing the HTML to the DIV
        newPopup.innerHTML = thisElementContent;
        newPopup.style.display='none';
        newPopup.style.width="100%";
        // Writing the Popup Div to popup div holder
        popupWrapper.appendChild(newPopup);
        $("#"+thisElementID).show("normal");
        
        // Making the AJAX call for the HTML content of the popup
        var params = {
            "element_id":newPopup.id,
            "request_type":$contentType,
            "h1":$h1_str,
            "popup_type":$popupType
        };
        
        inlinePopups[params.element_id] = false;
        // Only attaching the Extra Params If the $additionalParams is set as an array
        if(typeof $additionalParams == 'object'){ params.additional = $additionalParams; }
        var json = new JSON;
        
        if(customCallBack){
            json.request('popup_content',params,customCallBack,'','/libs/JSON/misc_actions.php');
        }else{
            json.request('popup_content',params,callback_popupContentDisplay,'','/libs/JSON/misc_actions.php');
        }
        videoBox_stopVideo('0');
    }
};

/* FILE: drop-down.js */
function dropDown(o) {
    // var subMenu = new Object();
    o.sub = o.parentNode.getElementsByTagName('ul')[0];
    o.sub.style.visibility = 'visible';
    o.sub.style.display = '';
    // actions
    if(o.sub.ddDelayKey!=null) { window.clearTimeout(o.sub.ddDelayKey); o.sub.ddDelayKey=null; }
    if (o.href.substr(o.href.length-1,1) == "#")
        o.onclick = function() { return false; }
    o.onmouseout = function() {
        if(!this.sub.ddDelayKey)
            this.sub.ddDelayKey = window.setTimeout(function() { o.sub.style.visibility='hidden'; o.sub.style.display = 'none'; } , 300);
    }
    o.sub.onmouseover = function() {
        if(o.sub.ddDelayKey!=null) { window.clearTimeout(o.sub.ddDelayKey); o.sub.ddDelayKey=null; }
        o.sub.style.visibility = 'visible';
        o.sub.style.display = '';
        o.sub.style.listStyle = 'none';
    }
    o.sub.onmouseout = function() {
        if(!this.ddDelayKey)
            this.ddDelayKey = window.setTimeout(function() { o.sub.style.visibility='hidden'; o.sub.style.display = 'none'; } , 300);
    }
}

function error_handler_by_id(error_id, error_string) {
    switch(error_id)
    {
        case(ERR_LOGIN):
            // Case makes the popup call for the login Element
            popup.login();
        break;
        case(ERR_INPUT):
        case(ERR_DELETED):
        case(ERR_DISABLED):
        case(ERR_FAILED):
        case(ERR_MISSING):
        case(ERR_LOGIN_INCORRECT):
        case(ERR_DENIED):
            alert(error_string);
        break;
        default:
            popup.report_bug(["AJAX error: "+error_string+"(#"+error_id+")"]);
        break;
    }
    return false;
}

var JSON_timeout = [];
var JSON = function () {
    this.xmlhttp=false;
    this.async=true;
    /*@cc_on @*/
    /*@if (@_jscript_version >= 5)
    try { this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) { try { this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { this.xmlhttp = false;}}
    @end @*/
    if (!this.xmlhttp && typeof XMLHttpRequest!='undefined') {try {this.xmlhttp = new XMLHttpRequest();} catch (e) {this.xmlhttp=false;}}
    if (!this.xmlhttp && window.createRequest) {try {this.xmlhttp = window.createRequest();} catch (e) {this.xmlhttp=false;}}
}
JSON.prototype.request = function ($data_type,$params_z,callback,section_type,file) {
    if (!file) file="/libs/JSON/JSON_actions.php";
    var string="";
    params_length=$params_z.length;
    string = "type="+$data_type+"&params="+JSON_parser.encode($params_z);
    if( section_type ) string += "&section_type="+section_type;
    
    var tempxmlhttp=this.xmlhttp;
    tempxmlhttp.open("POST",file, this.async);
    tempxmlhttp.setRequestHeader('Content-Type', "application/x-www-form-urlencoded");
    //tempxmlhttp.setRequestHeader("Content-Length", string.length);
    tempxmlhttp.onreadystatechange=function() {if (tempxmlhttp.readyState==4) {if (tempxmlhttp.status!=404) {callback(JSON_parser.decode(tempxmlhttp.responseText));} else {alert("JSON Call Failed!");}}}
    if (this.async) {
        if (JSON_timeout[$data_type]) clearTimeout(JSON_timeout[$data_type]);
        var timeoutFunc = function() { tempxmlhttp.send(string); }
        JSON_timeout[$data_type]=setTimeout(timeoutFunc,200);
    } else {
        tempxmlhttp.send(string);
        callback(JSON_parser.decode(tempxmlhttp.responseText));
    }
}

// This gets the top left positions of the clients scrolled window from the documents top left
// Also uses lazy function definition pattern.  It shows considerable speed improvements over not using it.
var getScrollVal = function() {
    if (typeof(window.pageXOffset) == 'number') {
        //Netscape compliant
        getScrollVal = function() {
            //alert('type 1' + window.pageXOffset+" "+window.pageYOffset);
            return [window.pageXOffset,window.pageYOffset];
        }
    }else if (document.documentElement && (typeof(document.documentElement.scrollLeft)=='number' || typeof(document.documentElement.scrollTop)=='number')) {
        //IE6 standards compliant mode
        getScrollVal = function() {
            //alert("Type stupid: " + document.documentElement.scrollLeft+" "+document.documentElement.scrollTop);
            return [document.documentElement.scrollLeft, document.documentElement.scrollTop];
        }
    }else if (document.body && (typeof(document.body.scrollLeft) == 'number' || typeof(document.body.scrollTop)=='number')) {
        //DOM compliant  (IE isn't DOM compliant...Have to put the IE6 one first)
        getScrollVal = function() {
            return [document.body.scrollLeft,document.body.scrollTop];
        }
    }
    return getScrollVal();
}

/**
 * This will regester a function to execute after the page load is completed
 *
 * @param {function} func the function that will be executed
 */
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

/**
* Function to control tab change 
* and handling a function as a parameter and it's own parameters
* 
* @param object Element which triggered the action ( this )
* @param string [optional] Function name, it must be already set in the page when this is triggered
* @param mixed  [optional] All parameters that should be passed to the function
* 
*/
function change_tabs() {
   if( arguments[1] && ( 'function' == typeof eval('window.' + arguments[1]) ) ) {
           myFunction = eval('window.' + arguments[1]);
        myArray = new Array();
        for(var i=2; i< arguments.length; i++)
            myArray[i-2] = arguments[i];
           myFunction( myArray );
   }
   
   var li = new Object();
   li = arguments[0];
   
   
   // Tab Management Here
   if(li.parentNode.nodeName=="UL") {
           if( typeof(ul_li)!='object') {
            var ul = li.parentNode;
            var ul_li = ul.getElementsByTagName('LI');
            for(i=0 ; i< ul_li.length ; i++) {
                ul_li[i].pos = i;
                if( ul_li[i].className.indexOf('onTab') !=-1) ul_li[i].parentNode.cur_tab = i;
                ul_li[i].onmouseout = function() {
                    if( this.parentNode.cur_tab!= this.pos) this.className = "offTab";
                }
            }
        }
   }
   
      if( li.className.indexOf('onTab') ==-1 )    li.className = "overTab";
    
       if( li.on_click == undefined) {
           li.on_click = ( li.onclick != undefined ) ? li.onclick : function() {};
        li.onclick = function() {
            activatetab( ul_li, this );
            return this.on_click();
        }
    }
}

function activatetab( ul_ar, liThis ) {
    if(liThis.id){
        var lastTab = ul_ar[liThis.parentNode.cur_tab];
        if(lastTab.id){
            $("#"+lastTab.id+"_content").hide();
        }
        $("#"+liThis.id+"_content").show();        
    }
    liThis.parentNode.cur_tab = liThis.pos;
    liThis.className = "onTab";
    for(i=0 ; i< ul_ar.length ; i++) {
        if( liThis.parentNode.cur_tab!= ul_ar[i].pos) ul_ar[i].className = "offTab";
    }
}

var videoBox_ar = new Array();
function videoBox_stopVideo($listing_id)
{
    // Looping though all flash elements that need to be set as logged in
    var videoBox_length = videoBox_ar.length;
    for(f=0; f<videoBox_length; f++){
        if(videoBox_ar[f] != $listing_id){
            if($("#"+videoBox_ar[f])[0]){
              var videoBox = getFlashMovieObject(videoBox_ar[f]);
              if(  videoBox && videoBox.clientHeight ){
                   videoBox.TPlay("/stop_listener_mc");
              }
            }else{
                videoBox_ar.splice(f,1);
            }
        }
    }
}

// Change the view type on the Listing Page
function listing_change_view( viewChosen ){
    listing_current_view = get_cookie('listing_view_choice');
    if(listing_current_view == null){
        if(viewChosen==undefined)   viewChosen = "visualMode";            // set default to listMode
    } else {
        if(viewChosen==undefined)   viewChosen = listing_current_view;  // set to the cookie choice
    }
    
    var oldView = listing_current_view;
    listing_current_view = viewChosen;
    set_cookie("listing_view_choice", listing_current_view,1);    // Changing The Cookie For The Users Choice: 
    
    if(viewChosen=='mapMode' || oldView=='mapMode') {
        window.location.reload();
    } else if ( $('#listing') ) {
        $('#listing').removeClass().addClass(viewChosen);
    }
}

// Change font size on the site
function font_size_change(size){
    set_cookie("font_size_choice", size);
    $('#wrapper').css({fontSize:size});
}

//    Function for Showing and hidding DIV while changing the label of the link
//        EXAMPLE:  onClick="hide_div(this, 'short list', 'tags_long');"
var hide_div_ar = new Array();
function hide_div_link_change(linkElement, replacement_txt, remove_div){
    var old_text = linkElement.innerHTML;
    linkElement.onclick=function() {
        hide_div_link_change(linkElement, old_text, remove_div);
        return false;
    }
    linkElement.innerHTML = replacement_txt;
    remove_div = $("#"+remove_div);
    if (remove_div.attr('class')=='widget_container_everything') {
        remove_div.removeClass().addClass('widget_container_topten');
    } else {
        remove_div.removeClass().addClass('widget_container_everything');
    }
}

/* Replace a DIVs inner HTML with a preloader that will be replaced with AJAX responses */
function enterPreLoader(element){
    if (element) element.innerHTML = '<img src="http://static.n49.ca/images/pre-loader.gif" border="0" class="preloader_image"/>';
}

/* Set the Opacity of a Element */
function setOpacity(element, value) {
    $("#"+element).fadeTo("fast", value/10);
}

/* Function: Clearing a Input Field
             NOTE: It only clears the field once.
             EXAMPLE:  onFocus="clear_input(this,'click here')" */
function clear_input(field, originalText){
    if (field.value == originalText) field.value = "";
    return false;
}

// Parse the current URL and return it in a neat little package.
function getCurrentURL() {
    var url_str = "" + window.location;
    var url_ar = {url:"",protocol:"",host:"",path:"",file:"", query:"", anchor:"", get:{}};

    // RegEx to get all URL elements parsed
    // split the differents elements of the URL
    var parse_url_e=/^((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)?(\?(.[^#\s]+))?(#.+)?$/;

    if (url_str.match(parse_url_e)) {
        url_ar = {url:RegExp['$&'], protocol:RegExp.$2, host:RegExp.$3, path:RegExp.$4, file:RegExp.$6, query:RegExp.$8, anchor:RegExp.$9, get:{}};
        var pairs = url_ar.query.split( /&/ );
        for(var i = 0 ;  i < pairs.length; i++) {
            var key_value = pairs[i].split( /=/ );
            url_ar.get[ key_value[0] ] = key_value[1];
        }
    }
    return url_ar;
}

// Return an object thats a flash movie
function getFlashMovieObject(movieName)
{
    if (window.document[movieName]) {
        return window.document[movieName];
    } else if (navigator.appName.indexOf("Microsoft Internet")==-1) {
        if (document.embeds && document.embeds[movieName])
        {
            return document.embeds[movieName];
        } 
    } else {// if (navigator.appName.indexOf("Microsoft Internet")!=-1)
        return $("#"+movieName)[0];
    }
}

// Does a Javascript confirm and redirects you to the url if true.
function confirmation(url, message) {
    if (confirm(message)){
       window.location = url;
    }
}

// Does a Javascript confirm and submits a form if true.
function delete_confirmation(form_name, item_name) {
    if (confirm('Are you sure you want to delete this ' + item_name + '?')) {
       if( deleted_form = $("#"+form_name) ) {
               deleted_form.submit();
       }
    }
}

// Gives a string for the current login state.  Used in flash things.
function getLoginString() {
    if (loggedin == true){
        return "true";
    }else{
        return "false";
    }
}
            
// Counts and limits the # of characters in a textarea.
function textCounter( field , cntfield , maxlimit ) {
    if (field.value.length > maxlimit)
        field.value = field.value.substring(0, maxlimit);
    else
        $("#"+cntfield).text(maxlimit - field.value.length);
}


// Read The Function Name :) It should be on the onmouseover of the div the embed is inside of 
function focusFlashMovie($element){
    if($element.firstChild){
        if(flashElements_ar[$element.id]){
            flashElements_ar[$element.id] = false;
            flashElements_ar[$element.id+"_embed"] = $element.id+"_embed";
        }
        $element.firstChild.id = $element.id+"_embed";
        forceRerendering($element.id);
        if(typeof $element.focus == 'function') {
            $element.focus()
        }
    }
}

// The following array will have items added to them to indicate if:
//     There were written on page load (AKA. Inline in the html)   - Will return true when called for
//     Or if the item in a pop up window (written by javascript)  - Will return false when called for
var inlinePopups = {};

/**
 * If the element this is called on is inside a popup, it'll return the ID of the popup its in.  Otherwise it'll false.
 * This is an upgraded version so that it can be used on -any- element inside a popup, instead of only the form element.
 * @param element $element A element (hopefully) inside of a popup
 */
function getPopUpWrapperId($element){   // Yuck.
    if ($element.id && ( $element.id.substr(0,13) == 'square_popup_' || $element.id.substr(0,13) == 'circle_popup_' )) {
        return $element.id;
    } else if ($element.parentNode) {
        return getPopUpWrapperId($element.parentNode);
    } else {
        return false;
    }
}

/**
God damnit.  This needs to be included for compatibility with the flash box
It uses the old stuff instead of the new stuff...ugh
 */
function popup_call($type, $additionalParams) {
    switch($type) {
        case('add_image'): popup.add_image($additionalParams); break;
        case('add_video'): popup.add_video($additionalParams); break;
        case('add_review'): popup.add_review($additionalParams); break;
    }
}

var popupIds = 0;
var popupTopZIndex = 10000;

function popup_display($popupType, $contentType, $h1_str, $additionalParams, customCallBack) {
    popup.display($popupType, $contentType, $h1_str, $additionalParams, customCallBack);
}

function callback_report_bug($data){
    return true;
}

popup_close = function ($elementID) {
    if (typeof $elementID == 'undefined') {
        what = this;
    } else if (typeof $elementID == 'string') {
        if (console) console.log('Deprecated use of popup_close.  Please revise.');
        what = "#"+$elementID;
    } else {
        what = $elementID;
    }
    $(what).fadeOut("normal", function(){ $("#popupWrapper").fadeOut("normal", function() { $('#fadeOver').fadeOut("normal"); } ).remove() });
}

/**
 * The Callback actions for popup_display
 * Checks for errors and closes the popup that was created for it if there are any
 * If there are no errors it sets the HTML, the display to 'block' and puts the popup on the top
 *
 * @param array $data [elementID, html] 
 */
function callback_popupContentDisplay($data, close_fn){
    if($data){
        if($data.err_code){
            // popup_close_all();
            error_handler_by_id($data.err_code, $data.err_str);
        }else{
            var popup         = $("#"+$data.elementID);
            var popup_content = $('#popup_content_'+$data.elementID);
            var popup_element = $('#popup_element_'+$data.elementID);
            
            popup_content.html($data.html);
            var top = getScrollVal()[1] + 20;
            popup_element.css({visibility:"visible", opacity:0.1,"top":top});
            popup_element.animate({opacity:1}, "normal");
            if($('#username')[0])    $('#username').focus();
            popup.css({zIndex:popupTopZIndex});
            popupTopZIndex ++;
            
            var params = { wmode: "transparent", quality: "high" };
            var flashvars = { title:$data.h1_str };
            swfobject.embedSWF("/swf/popup_h1_"+$data.popupType+".swf", 'popup_h1_flash_'+$data.elementID, "100%", "26", "8", '', flashvars, params);
            if (typeof close_fn != "undefined") {
                popup[0].close = function() {
                    close_fn();
                    popup_close(this);
                }
            } else {
                popup[0].close = popup_close;
            }
        }
    }
}

/**
 * The Custom Popup Callback actions for add_video
 * Checks for errors and closes the popup that was created for it if there are any
 * If there are no errors uses callback_popupContentDisplay to populate the popup
 * It then writes the flash video player and the stars  
 *  
 * @param array $data [html, video_id, path]
 */
function callback_add_video($data){
    if($data){
        if($data.err_code){
            popup_close_all();
            error_handler_by_id($data.err_code, $data.err_str);
        }else{
            callback_popupContentDisplay($data);
            var videoUploads = $('#videoUploads');
            if(videoUploads){
                var add_video_upload_status = false;

                var params = { wmode:"transparent", quality:"high" };
                var flashvars = { user_id:$data.member_id, type:$data.type, id:$data.type_id, loggedin:getLoginString()};

                swfobject.embedSWF("/swf/video_uploader.swf", "videoUploads", "520", "180", "8", '', flashvars, params);
            }
        }
    }
}

/**
 * The Custom Popup Callback actions for image_enlarge
 * Checks for errors and closes the popup that was created for it if there are any
 * If there are no errors uses callback_popupContentDisplay to populate the popup
 * It then writes the stars  
 *  
 * @param array $data [html, image_id, path]
 */
function callback_image_enlarge($data){
    if($data){
        if($data.err_code){
            popup_close_all();
            error_handler_by_id($data.err_code, $data.err_str);
        }else{
            if(!$('#image_enlarge')[0]){
                $data.html = '<div id="image_enlarge">'+$data.html+'</div>';
                callback_popupContentDisplay($data);
                $("#"+$data.elementID).css({visibility:"hidden"});
            }else{
                popup_close_all();
                $('#image_enlarge').html($data.html);
            }
    
            var params = { wmode: "transparent", quality: "high" };
            var flashvars = {rating:$data.rating, id:$data.image_id, rating_type:"image", loggedin:getLoginString()};

            var divID = "image_enlarge_stars";
            swfobject.embedSWF("/swf/rating.swf", divID, "70", "15", "6", '', flashvars, params);

            flashElements_ar.push(divID);
        }
    }
}

/**
 * The Custom Popup Callback actions for video_enlarge
 * Checks for errors and closes the popup that was created for it if there are any
 * If there are no errors uses callback_popupContentDisplay to populate the popup
 * It then writes the flash video player and the stars  
 *  
 * @param array $data [html, video.video_id, video.path, video.rating]
 */
function callback_video_enlarge($data){
    if($data){
        if($data.err_code){
            popup_close_all();
            error_handler_by_id($data.err_code, $data.err_str);
        }else{
            if(!$('#video_enlarge')[0]){
                $data.html = '<div id="video_enlarge">'+$data.html+'</div>';
                callback_popupContentDisplay($data);
            }else{
                popup_close_all();
                $('#video_enlarge').html($data.html);
            }
            callback_popupContentDisplay($data);
            
            var params = { wmode: "transparent", quality: "high" };
            var flashvars = {video_path:$data.video.path, fullScreen:"false"};

            var divID = "video_player_large";
            swfobject.embedSWF("/swf/mediaplayer.swf", divID, "525", "415", "9.0.47", '', flashvars, params);

            videoBox_ar.push(divID);
            stars.init('stars_video_'+$data.video.video_id, 'video', $data.video.video_id);
        }
    }
}


function callback_reviewBusinessDisplay($data){
    if($data){
        if($data.err_code){
            popup_close_all();
            error_handler_by_id($data.err_code, $data.err_str);
        }else{
            callback_popupContentDisplay($data);
            var params = { wmode: "transparent", quality: "high" };
            var flashvars = {};
            flashvars.rating = $data.rating;
            flashvars.rating_type = "hidden_field";
            flashvars.loggedin = "true";
            swfobject.embedSWF("/swf/rating.swf", "rating_element", "140", "30", "6", '', flashvars, params);
            var rating = document.createElement("input");                        
            rating.id    = "rating";
            rating.name  = "params[4]";
            rating.type  = "hidden";
            if($data.rating){
                rating.value = $data.rating;
            }else{
                rating.value = 0;
            }
            rating.onMouseDown = function(){ clearDragObject(); }
            $('#rating_hidden_holder').append(rating);
        }
    }
}

function flashSetRating(value) { 
   $('#rating').attr('value', value);
}

// Closes all open popup windows.
function popup_close_all(e){
    var use_event = null;
    if (typeof e != 'undefined') {
        use_event = e;
    } else if (typeof window.event != 'undefined') {
        use_event = window.event;
    }
    if (use_event) {
        if (typeof use_event.preventDefault != 'undefined') {
            use_event.preventDefault();
        }
    }
    try { 
        $('#popupWrapper').children().each(function(that){ if (typeof this.close == "function") { this.close(); } else { $(this).fadeOut(); } });
    } catch (E){console.log(E);}
    $("#fadeOver").fadeOut('normal', function() {
        $("#popupWrapper").fadeOut('normal', function() {
            $("#popupWrapper").remove();
        })
    });
}

// Used to populate the right column with tags
function tags_populate_right_col(section,type,title,tags) {
    // tags_right_col => defined in the main page
    if( $('#rcol_tags_title') ){
        // if(!tags_right_col) var tags_right_col = new Array();
        // Cache the data to prevent another JSON call
        if(!tags_right_col[section])        tags_right_col[section] = new Array();
        if(!tags_right_col[section][type])  tags_right_col[section][type] = new Array();
        
        if(!tags_right_col[section][type]['title']) {
            tags_right_col[section][type]['title'] = title;
            tags_right_col[section][type]['data'] = tags;
        }
        
        if( title || tags_right_col[section][type]['title'] ) {
            if( tags_right_col[section][type] && typeof title=="undefined" ) {
                title = tags_right_col[section][type]['title'];
                tags  = tags_right_col[section][type]['data'];
            }
            $('#rcol_tags_title').text(title);
            var tagList ='';
            for( i=0; i<tags.length ; i++ ) {
                tagList += '<li><a title="'+ tags[i].title +'" style="font-size:'+ tags[i].size +'%;" class="'+ tags[i].shade +'" href="'+ tags[i].link +'">'+ tags[i].name +'</a></li>'+"\n";
            }
            $('#rcol_tags_list').html(tagList);
        }
    }
}

// Used for adding a favourite
function submit_add_favourites($element){
    var params = new Array();
    params[0] = $('#tags').attr('value');
    params[1] = $('#public_private').attr('value');
    params[2] = $('#fav_type').attr('value');
    params[3] = $('#type_id').attr('value');
    params[4] = $('#type').attr('value');
    params[5] = $('#from_id').attr('value');
    params[6] = getPopUpWrapperId($element);
    var json = new JSON;
    // alert(params);
    json.request('add_favourite',params,callback_submit_add_favourites,'','/libs/JSON/member_actions.php');
    return false;
}

// The Callback from submit_report_bug()
function callback_submit_add_favourites($data) {
    if ($data.err_code) {
        error_handler_by_id($data.err_code, $data.err_str)
    }else{
        var url_ar = getCurrentURL();
        if(url_ar['file'] != 'actions.php'){
            // Close the login popup window
            popup_close_all();
        }else{
           var redirectLocation = '/members/';
           if($('#referer')[0]){ redirectLocation = $('#referer').attr('value'); }
           window.document.location = redirectLocation;
        }
    }
}

// Deletes a listing from a member's favourites.
function request_delete_favourites($type, $id, $element){
    var answer = confirm('Are you sure you want to delete this favourite?');
    if (answer){
        enterPreLoader($element);
        $element.innerHTML += '<p align="center">deleting favourite</p>';
        var params = new Array();
        params[0] = $id;
        params[1] = $type;
        params[2] = $element.id;
        var json = new JSON;
        json.request('delete_favourite',params,callback_delete_favourites,'','/libs/JSON/member_actions.php') ;
    }
}

// The callback from request_delete_favourites
function callback_delete_favourites($data){
    if($data.err_code) {
        error_handler_by_id($data.err_code);
    } else {
       var element = $("#"+$data.elementID).remove();

       // Changing all the favourites count tags based on the favourites type
       var spans = document.getElementsByName('num_favouritess_'+$data.type);
       var length = spans.length;
       for(i = 0; i < length; i += 1){
           spans[i].innerHTML = $data.count;
       }

    }
}

// Used for editing a favourite listing
function submit_tags_edit($element){
    var params = new Array();
    params[0] = $('#tags').attr('value');
    params[1] = $('#public_private').attr('value');
    params[2] = $('#fav_type').attr('value');
    params[3] = $('#id').attr('value');
    params[4] = getPopUpWrapperId($element);
    var json = new JSON;
    // alert(params);
    json.request('submit_tags_edit',params,callback_submit_tags_edit,'','/libs/JSON/tags_actions.php');
    return false;
}

// Used for editing a favourite listing
function callback_submit_tags_edit($data){
    if($data.err_code) {
        error_handler_by_id($data.err_code);
    } else {
        popup_close_all();
        window.location.reload();
    }
}

// Removes a item from the DOM
function remove_element($element){
    if($element) { $element.parentNode.removeChild($element); }
}

// Edits the adword iframes
function changeAdSense(){
    var googleAds = document.getElementsByName('google_ads_frame');
    var googleLen = googleAds.length;
    for(var i=0;i<googleLen;i++){if(googleAds[i].height == '60' && googleAds[i].width == '468'){googleAds[i].height = '40';}}
}

var JSON_parser = new function(){
    var useHasOwn = {}.hasOwnProperty?true:false;
    var pad = function(n) { return n < 10 ? '0' + n : n; };
    var m = {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\', '&' : '%26', '+' : '%2B' };
    var encodeString = function(s){if (/[&\+"\\\x00-\x1f]/.test(s)) {return '"' + s.replace(/([&\+"\\\x00-\x1f])/g, function(a, b) {var c = m[b];if(c) return c;c = b.charCodeAt();return '\\u00'+Math.floor(c / 16).toString(16)+(c % 16).toString(16);}) + '"';}return '"' + s + '"';};
    var encodeArray = function(o){var a = ['['], b, i, l = o.length, v;for (i = 0; i < l; i += 1) {v = o[i];switch (typeof v) {case 'undefined':case 'function':case 'unknown': break;default:if (b) {a.push(',');}a.push(v === null ? "null" : JSON_parser.encode(v));b = true;}}a.push(']');return a.join('');};
    var encodeDate = function(o){return '"' + o.getFullYear() + '-' +pad(o.getMonth() + 1) + '-' +pad(o.getDate()) + 'T' +pad(o.getHours()) + ':' +pad(o.getMinutes()) + ':' +pad(o.getSeconds()) + '"';};
    this.encode = function(o){if(typeof o == 'undefined' || o === null){return 'null';}else if(o instanceof Array){return encodeArray(o);}else if(o instanceof Date){return encodeDate(o);}else if(typeof o == 'string'){return encodeString(o);}else if(typeof o == 'number'){return isFinite(o) ? String(o) : "null";}else if(typeof o == 'boolean'){return String(o);}else {var a = ['{'], b, i, v;for (var i in o) {if(!useHasOwn || o.hasOwnProperty(i)) {v = o[i];switch (typeof v) {case 'undefined':case 'function':case 'unknown':break;default:if(b){a.push(',');}a.push(this.encode(i), ':',v === null ? "null" : this.encode(v));b = true;}}}a.push('}');return a.join('');}};
    this.decode = function(json){var result = json;if (json.substr(0,9)=="while(1);") json = json.substring(9);var reg_json = /\<br \/\>([\w\W]*)\<br \/\>/;if(result.match(reg_json)){popup.report_bug(["JSON Repsonse error: "+RegExp.$1]);}else{return new Function("return "+json)();}};
}();

function rating_stars(swfPath,ratingType,ratingID,rating,image_id,width,height) {
    if(width==undefined) width=70;
    if(height==undefined) height=15;

    var params = { wmode: "transparent", quality: "high" };
    var flashvars = {};
    flashvars.rating        = rating;
    flashvars.id            = image_id;
    flashvars.rating_type   = ratingType;
    flashvars.loggedin      = getLoginString();

    swfobject.embedSWF(swfPath, ratingID, width, height, "6", '', flashvars, params);
}

/**
 * SWFObject v2.1: Flash Player detection and embed - http://code.google.com/p/swfobject/wiki/documentation
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
var swfobject=function(){var b="undefined",Q="object",n="Shockwave Flash",p="ShockwaveFlash.ShockwaveFlash",P="application/x-shockwave-flash",m="SWFObjectExprInst",j=window,K=document,T=navigator,o=[],N=[],i=[],d=[],J,Z=null,M=null,l=null,e=false,A=false;var h=function(){var v=typeof K.getElementById!=b&&typeof K.getElementsByTagName!=b&&typeof K.createElement!=b,AC=[0,0,0],x=null;if(typeof T.plugins!=b&&typeof T.plugins[n]==Q){x=T.plugins[n].description;if(x&&!(typeof T.mimeTypes!=b&&T.mimeTypes[P]&&!T.mimeTypes[P].enabledPlugin)){x=x.replace(/^.*\s+(\S+\s+\S+$)/,"$1");AC[0]=parseInt(x.replace(/^(.*)\..*$/,"$1"),10);AC[1]=parseInt(x.replace(/^.*\.(.*)\s.*$/,"$1"),10);AC[2]=/r/.test(x)?parseInt(x.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof j.ActiveXObject!=b){var y=null,AB=false;try{y=new ActiveXObject(p+".7")}catch(t){try{y=new ActiveXObject(p+".6");AC=[6,0,21];y.AllowScriptAccess="always"}catch(t){if(AC[0]==6){AB=true}}if(!AB){try{y=new ActiveXObject(p)}catch(t){}}}if(!AB&&y){try{x=y.GetVariable("$version");if(x){x=x.split(" ")[1].split(",");AC=[parseInt(x[0],10),parseInt(x[1],10),parseInt(x[2],10)]}}catch(t){}}}}var AD=T.userAgent.toLowerCase(),r=T.platform.toLowerCase(),AA=/webkit/.test(AD)?parseFloat(AD.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,q=false,z=r?/win/.test(r):/win/.test(AD),w=r?/mac/.test(r):/mac/.test(AD);/*@cc_on q=true;@if(@_win32)z=true;@elif(@_mac)w=true;@end@*/return{w3cdom:v,pv:AC,webkit:AA,ie:q,win:z,mac:w}}();var L=function(){if(!h.w3cdom){return }f(H);if(h.ie&&h.win){try{K.write("<script id=__ie_ondomload defer=true src=//:><\/script>");J=C("__ie_ondomload");if(J){I(J,"onreadystatechange",S)}}catch(q){}}if(h.webkit&&typeof K.readyState!=b){Z=setInterval(function(){if(/loaded|complete/.test(K.readyState)){E()}},10)}if(typeof K.addEventListener!=b){K.addEventListener("DOMContentLoaded",E,null)}R(E)}();function S(){if(J.readyState=="complete"){J.parentNode.removeChild(J);E()}}function E(){if(e){return }if(h.ie&&h.win){var v=a("span");try{var u=K.getElementsByTagName("body")[0].appendChild(v);u.parentNode.removeChild(u)}catch(w){return }}e=true;if(Z){clearInterval(Z);Z=null}var q=o.length;for(var r=0;r<q;r++){o[r]()}}function f(q){if(e){q()}else{o[o.length]=q}}function R(r){if(typeof j.addEventListener!=b){j.addEventListener("load",r,false)}else{if(typeof K.addEventListener!=b){K.addEventListener("load",r,false)}else{if(typeof j.attachEvent!=b){I(j,"onload",r)}else{if(typeof j.onload=="function"){var q=j.onload;j.onload=function(){q();r()}}else{j.onload=r}}}}}function H(){var t=N.length;for(var q=0;q<t;q++){var u=N[q].id;if(h.pv[0]>0){var r=C(u);if(r){N[q].width=r.getAttribute("width")?r.getAttribute("width"):"0";N[q].height=r.getAttribute("height")?r.getAttribute("height"):"0";if(c(N[q].swfVersion)){if(h.webkit&&h.webkit<312){Y(r)}W(u,true)}else{if(N[q].expressInstall&&!A&&c("6.0.65")&&(h.win||h.mac)){k(N[q])}else{O(r)}}}}else{W(u,true)}}}function Y(t){var q=t.getElementsByTagName(Q)[0];if(q){var w=a("embed"),y=q.attributes;if(y){var v=y.length;for(var u=0;u<v;u++){if(y[u].nodeName=="DATA"){w.setAttribute("src",y[u].nodeValue)}else{w.setAttribute(y[u].nodeName,y[u].nodeValue)}}}var x=q.childNodes;if(x){var z=x.length;for(var r=0;r<z;r++){if(x[r].nodeType==1&&x[r].nodeName=="PARAM"){w.setAttribute(x[r].getAttribute("name"),x[r].getAttribute("value"))}}}t.parentNode.replaceChild(w,t)}}function k(w){A=true;var u=C(w.id);if(u){if(w.altContentId){var y=C(w.altContentId);if(y){M=y;l=w.altContentId}}else{M=G(u)}if(!(/%$/.test(w.width))&&parseInt(w.width,10)<310){w.width="310"}if(!(/%$/.test(w.height))&&parseInt(w.height,10)<137){w.height="137"}K.title=K.title.slice(0,47)+" - Flash Player Installation";var z=h.ie&&h.win?"ActiveX":"PlugIn",q=K.title,r="MMredirectURL="+j.location+"&MMplayerType="+z+"&MMdoctitle="+q,x=w.id;if(h.ie&&h.win&&u.readyState!=4){var t=a("div");x+="SWFObjectNew";t.setAttribute("id",x);u.parentNode.insertBefore(t,u);u.style.display="none";var v=function(){u.parentNode.removeChild(u)};I(j,"onload",v)}U({data:w.expressInstall,id:m,width:w.width,height:w.height},{flashvars:r},x)}}function O(t){if(h.ie&&h.win&&t.readyState!=4){var r=a("div");t.parentNode.insertBefore(r,t);r.parentNode.replaceChild(G(t),r);t.style.display="none";var q=function(){t.parentNode.removeChild(t)};I(j,"onload",q)}else{t.parentNode.replaceChild(G(t),t)}}function G(v){var u=a("div");if(h.win&&h.ie){u.innerHTML=v.innerHTML}else{var r=v.getElementsByTagName(Q)[0];if(r){var w=r.childNodes;if(w){var q=w.length;for(var t=0;t<q;t++){if(!(w[t].nodeType==1&&w[t].nodeName=="PARAM")&&!(w[t].nodeType==8)){u.appendChild(w[t].cloneNode(true))}}}}}return u}function U(AG,AE,t){var q,v=C(t);if(v){if(typeof AG.id==b){AG.id=t}if(h.ie&&h.win){var AF="";for(var AB in AG){if(AG[AB]!=Object.prototype[AB]){if(AB.toLowerCase()=="data"){AE.movie=AG[AB]}else{if(AB.toLowerCase()=="styleclass"){AF+=' class="'+AG[AB]+'"'}else{if(AB.toLowerCase()!="classid"){AF+=" "+AB+'="'+AG[AB]+'"'}}}}}var AD="";for(var AA in AE){if(AE[AA]!=Object.prototype[AA]){AD+='<param name="'+AA+'" value="'+AE[AA]+'" />'}}v.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+AF+">"+AD+"</object>";i[i.length]=AG.id;q=C(AG.id)}else{if(h.webkit&&h.webkit<312){var AC=a("embed");AC.setAttribute("type",P);for(var z in AG){if(AG[z]!=Object.prototype[z]){if(z.toLowerCase()=="data"){AC.setAttribute("src",AG[z])}else{if(z.toLowerCase()=="styleclass"){AC.setAttribute("class",AG[z])}else{if(z.toLowerCase()!="classid"){AC.setAttribute(z,AG[z])}}}}}for(var y in AE){if(AE[y]!=Object.prototype[y]){if(y.toLowerCase()!="movie"){AC.setAttribute(y,AE[y])}}}v.parentNode.replaceChild(AC,v);q=AC}else{var u=a(Q);u.setAttribute("type",P);for(var x in AG){if(AG[x]!=Object.prototype[x]){if(x.toLowerCase()=="styleclass"){u.setAttribute("class",AG[x])}else{if(x.toLowerCase()!="classid"){u.setAttribute(x,AG[x])}}}}for(var w in AE){if(AE[w]!=Object.prototype[w]&&w.toLowerCase()!="movie"){F(u,w,AE[w])}}v.parentNode.replaceChild(u,v);q=u}}}return q}function F(t,q,r){var u=a("param");u.setAttribute("name",q);u.setAttribute("value",r);t.appendChild(u)}function X(r){var q=C(r);if(q&&(q.nodeName=="OBJECT"||q.nodeName=="EMBED")){if(h.ie&&h.win){if(q.readyState==4){B(r)}else{j.attachEvent("onload",function(){B(r)})}}else{q.parentNode.removeChild(q)}}}function B(t){var r=C(t);if(r){for(var q in r){if(typeof r[q]=="function"){r[q]=null}}r.parentNode.removeChild(r)}}function C(t){var q=null;try{q=K.getElementById(t)}catch(r){}return q}function a(q){return K.createElement(q)}function I(t,q,r){t.attachEvent(q,r);d[d.length]=[t,q,r]}function c(t){var r=h.pv,q=t.split(".");q[0]=parseInt(q[0],10);q[1]=parseInt(q[1],10)||0;q[2]=parseInt(q[2],10)||0;return(r[0]>q[0]||(r[0]==q[0]&&r[1]>q[1])||(r[0]==q[0]&&r[1]==q[1]&&r[2]>=q[2]))?true:false}function V(v,r){if(h.ie&&h.mac){return }var u=K.getElementsByTagName("head")[0],t=a("style");t.setAttribute("type","text/css");t.setAttribute("media","screen");if(!(h.ie&&h.win)&&typeof K.createTextNode!=b){t.appendChild(K.createTextNode(v+" {"+r+"}"))}u.appendChild(t);if(h.ie&&h.win&&typeof K.styleSheets!=b&&K.styleSheets.length>0){var q=K.styleSheets[K.styleSheets.length-1];if(typeof q.addRule==Q){q.addRule(v,r)}}}function W(t,q){var r=q?"visible":"hidden";if(e&&C(t)){C(t).style.visibility=r}else{V("#"+t,"visibility:"+r)}}function g(s){var r=/[\\\"<>\.;]/;var q=r.exec(s)!=null;return q?encodeURIComponent(s):s}var D=function(){if(h.ie&&h.win){window.attachEvent("onunload",function(){var w=d.length;for(var v=0;v<w;v++){d[v][0].detachEvent(d[v][1],d[v][2])}var t=i.length;for(var u=0;u<t;u++){X(i[u])}for(var r in h){h[r]=null}h=null;for(var q in swfobject){swfobject[q]=null}swfobject=null})}}();return{registerObject:function(u,q,t){if(!h.w3cdom||!u||!q){return }var r={};r.id=u;r.swfVersion=q;r.expressInstall=t?t:false;N[N.length]=r;W(u,false)},getObjectById:function(v){var q=null;if(h.w3cdom){var t=C(v);if(t){var u=t.getElementsByTagName(Q)[0];if(!u||(u&&typeof t.SetVariable!=b)){q=t}else{if(typeof u.SetVariable!=b){q=u}}}}return q},embedSWF:function(x,AE,AB,AD,q,w,r,z,AC){if(!h.w3cdom||!x||!AE||!AB||!AD||!q){return }AB+="";AD+="";if(c(q)){W(AE,false);var AA={};if(AC&&typeof AC===Q){for(var v in AC){if(AC[v]!=Object.prototype[v]){AA[v]=AC[v]}}}AA.data=x;AA.width=AB;AA.height=AD;var y={};if(z&&typeof z===Q){for(var u in z){if(z[u]!=Object.prototype[u]){y[u]=z[u]}}}if(r&&typeof r===Q){for(var t in r){if(r[t]!=Object.prototype[t]){if(typeof y.flashvars!=b){y.flashvars+="&"+t+"="+r[t]}else{y.flashvars=t+"="+r[t]}}}}f(function(){U(AA,y,AE);if(AA.id==AE){W(AE,true)}})}else{if(w&&!A&&c("6.0.65")&&(h.win||h.mac)){A=true;W(AE,false);f(function(){var AF={};AF.id=AF.altContentId=AE;AF.width=AB;AF.height=AD;AF.expressInstall=w;k(AF)})}}},getFlashPlayerVersion:function(){return{major:h.pv[0],minor:h.pv[1],release:h.pv[2]}},hasFlashPlayerVersion:c,createSWF:function(t,r,q){if(h.w3cdom){return U(t,r,q)}else{return undefined}},removeSWF:function(q){if(h.w3cdom){X(q)}},createCSS:function(r,q){if(h.w3cdom){V(r,q)}},addDomLoadEvent:f,addLoadEvent:R,getQueryParamValue:function(v){var u=K.location.search||K.location.hash;if(v==null){return g(u)}if(u){var t=u.substring(1).split("&");for(var r=0;r<t.length;r++){if(t[r].substring(0,t[r].indexOf("="))==v){return g(t[r].substring((t[r].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(A&&M){var q=C(m);if(q){q.parentNode.replaceChild(M,q);if(l){W(l,true);if(h.ie&&h.win){M.style.display="block"}}M=null;l=null;A=false}}}}}();

// Facebook link script
// e.g.: a href="http://www.facebook.com/share.php?u=<url>" onclick="return fbs_click()" target="_blank" class="fb_share_link">Share on Facebook</a>
function fbs_click() {u=location.href;t=document.title;window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;}

/**
 * Used for submiting a login attempt to PHP with AJAX.
 * @params {object}  $element The form thats being submited
*/
function loginPopup($element)
{
    if( $('#popupLoginError') ) { $('#popupLoginError').hide(); }
    var params = new Array();
    params[0] = $element.elements[0].value; // username
    params[1] = $element.elements[1].value; // password
    params[2] = 'popupLoginError';
    params[3] = getPopUpWrapperId($element);
    var json = new JSON;
    json.request('login',params,login_callback,'','/libs/JSON/member_actions.php');
    return false;
}

// duplicate of the above function. For some reason the left widget can't use the above, going to fix it.
function loging($element){
    if( $('#menuLoginError') ) { $('#menuLoginError').hide(); }
    var params = new Array();
    params[0] = $element.elements[0].value; // username
    params[1] = $element.elements[1].value; // password
    params[2] = 'menuLoginError';
    var json = new JSON;
    json.request('login',params,login_callback,'','/libs/JSON/member_actions.php');
    return false;
}

// resend confirmation in case the user didn't get the e-mail to valid the account
function resendConfirmation(from){
    if( from && (from=='popup' || from=='menu') ) {
        $element = $("#"+from+'LoginForm'); // access the data of the right form
        var params = new Array();
        params[0] = $element.children()[0].value; // username
        params[1] = $element.cildren()[1].value; // password
        params[2] = from + 'LoginError';
        var json = new JSON;
        json.request('resendConfirmationMail',params,login_callback,'','/libs/JSON/member_actions.php');
        return false;
    }
}

function login_callback($data) {
    if ($data.err_str) { if( $("#"+$data.errorSlot) ) { $("#"+$data.errorSlot).html($data.err_str); $("#"+$data.errorSlot).css({display:"block"});} }
    else {window.location.reload();}
    return false;
}

// Handles the return from a call to update the members details on stage
function callback_memberDetails(data){
    if (data.err_code) {
        error_handler_by_id(data.err_code, data.err_str)
    }else{
        $('#menu_username').html("<a href=\"#\" class=\"redLink\">"+data.username+"</a>");
        $('#menu_signUp_logOut').html("<a href=\"/logout.php\" class=\"redLink\">LOG OUT</a>");
    }
    return false;
}

function sendsms($company_id,element) {
    if ($company_id) {
        params=[ $company_id, $('#destphone').attr('value') ];
        
        if ($('#destmesg')[0]) {
            params[2] = $('#destmesg').attr('value');
        }
        params[3] = getPopUpWrapperId(element.parentNode.parentNode);
        if ($('#captcha_hash')[0]) {
            params[4] = $('#captcha_hash').attr('value');
        }
        if ($('#captcha_input')[0]) {
            params[5] = $('#captcha_input').attr('value');
        }
        json=new JSON;
        json.request('send_sms', params, callback_sendsms, '', '/libs/JSON/misc_actions.php');
    }
    return false;
}

function callback_sendsms (data) {
    if (data.err_code) {
        error_handler_by_id(data.err_code, data.err_str)
    } else {
        //alert(data['message']);
        popup_close_all();
    }
    return false;
}

// Stolen from: http://www.somacon.com/p355.php
// I like trim.  Trim is nice.
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

if (typeof $ != 'undefined') {
    $(document).ready(function() {
        window.setTimeout(function() {
            $('.status_box').fadeTo(1000, 0, function() {
                $('.status_box').slideUp(100);
            });
        }, 5000);
    });
}

// Let's define my error codes...
ERR_INPUT=1; ERR_LOGIN=2;ERR_DELETED=3;ERR_DISABLED=4;ERR_FAILED=5;ERR_MISSING=6;ERR_LOGIN_INCORRECT=7;ERR_DENIED=8;


var stars={
    init:function($div_id, $type, $type_id, $style) {
        if (typeof $style == 'undefined') $style='small';
        
        if (typeof $style == 'object' || typeof $style == 'function') {
            $step = $style;
        } else if (typeof $style == 'string') {
            if ($style == 'big') {
                var $step = {x:15, y:30};
            } else if ($style == 'medium') {
                var $step = {x:10, y:20};
            } else {
                var $step = {x:7, y:14};
            }
        } else {
            return; // You obviously passed in something crazy.
        }
        
        $('#'+$div_id).
            data("type", $type).
            data("type_id", $type_id).
            data("step", $step).
            click(stars.rate).
            mousemove(stars.hover).
            mouseleave(stars.reset).
            css('cursor', 'pointer');
    },
    hover:function(e) {
        var div = $(e.currentTarget);
        var my_position = div.offset();
        var $x = e.clientX - my_position.left;
        var $w = div.width();
        var $step = div.data("step");
        
        var pct_full = ($x/$w)*100;
        var real_rating = pct_full/10;
        var rounded_rating = (Math.ceil(pct_full/5)*5)/10;  // Round to the nearest .5
        
        //console.log(pct_full, $x, $w, rounded_rating, real_rating);
        
        $y = $x / ($step.x / $step.y);  // This produces a neat rolling effect
        // Let's lock it into the steps
        $y = Math.ceil($y/$step.y)*$step.y;
        
        div.children(".star_rating").css("top", -$y);
        return rounded_rating;
    },
    reset:function(e) {
        $(this).children(".star_rating").attr('style', '');
    },
    rate:function(e) {
        $rating = stars.hover(e);
        $type = $(this).data("type");
        $type_id = $(this).data("type_id");
        $div_id = $(this).attr('id');
        
        $(this).unbind('click').unbind('mousemove').unbind('mouseleave').css('cursor', 'auto');
        var params = {
            "type":$type,
            "type_id":$type_id,
            "rating":$rating,
            "div_id":$div_id
        }
        console.log(params);
        var json = new JSON;
        json.request($type, params, stars.rate_callback, '', '/libs/JSON/rating_actions.php');
    },
    rate_callback:function($data) {
        if ($data.err_code) {
            return error_handler_by_id($data.err_code, $data.err_str);
        }
        
        var rating_string = $data.new_rating.toString().replace(".", "_");
        $("#"+$data.div_id).children(".star_rating").removeClass('rate_0 rate_0_5 rate_1 rate_1_5 rate_2 rate_2_5 rate_3 rate_3_5 rate_4 rate_4_5 rate_5').addClass('rate_'+rating_string);
        stars.reset($data.div_id);
    }
}