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(conf.jsurl + 'content_display/login.js');
        returnValue = document.URL;
        loginPage = "/login/?return_to=" + encodeURIComponent(returnValue);
        window.location = loginPage;
            
        //this.display('square', 'login', 'LOGIN');
    },
    forgot_password:function() {
        this.display('square', 'forgot_password', 'FORGOT PASSWORD?');
    },
    tags_what:function() {
        this.display('square', 'tags_what', 'WHAT ARE TAGS?');
    },
    tags_why:function() {
        this.display('square', 'tags_why', 'WHY USE TAGS?');
    },
    tags_edit:function($additionalParams) {
        this.display('square', 'tags_edit', 'EDIT TAGS', $additionalParams );
    },
    image_enlarge:function($additionalParams) {
        loadScript(conf.jsurl + '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(conf.jsurl + 'content_display/videos.js');
        this.display('square', 'video_enlarge', 'VIDEO GALLERY', $additionalParams, callback_video_enlarge);
    },
    quick_quote:function($additionalParams) {
        loadScript(conf.jsurl + 'content_display/quick_quote.js');
        this.display('square', 'quick_quote', 'QUICK QUOTE', $additionalParams);
    },
    email_business:function($additionalParams) {
        loadScript(conf.jsurl + '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(conf.jsurl + '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(conf.jsurl + '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(conf.jsurl + 'content_display/add_review.js');
            loadScript(conf.jsurl + 'content_display/reviews.js');
            this.display('square', 'add_review', 'REVIEW THIS BUSINESS', $additionalParams, callback_reviewBusinessDisplay);
        }
    },
    review_comment:function($additionalParams) {
        loadScript(conf.jsurl + 'content_display/reviews.js');
        this.display('square', 'review_comment', 'COMMENT ON THIS REVIEW', $additionalParams);
    },
    article_comment:function($additionalParams) {
        loadScript(conf.jsurl + 'content_display/articles.js');
        this.display('square', 'article_comment', 'COMMENT ON THIS ARTICLE', $additionalParams);
    },
    attach_article:function($additionalParams) {
        loadScript(conf.jsurl + 'content_display/articles.js');
        this.display('square', 'attach_article', 'ATTACH THIS ARTICLE', $additionalParams);
    },
    lead_comment:function($additionalParams) {
        loadScript(conf.jsurl + 'content_display/leads.js');
        this.display('square', 'lead_comment', 'EDIT COMMENT', $additionalParams);
    },
    edit_elt_txt:function ($additionalParams) {
        loadScript(conf.jsurl + 'content_display/edit_caption.js');
        this.display('square', 'edit_elt_txt', 'EDIT CAPTION', $additionalParams);
    },
    email_friend:function ($additionalParams) {
        loadScript(conf.jsurl + '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(conf.jsurl + 'content_display/members.js');
        this.display('square', 'add_friend', 'ADD A FRIEND', $additionalParams);
    },
    inappropriate:function ($additionalParams) {
        loadScript(conf.jsurl + 'content_display/inappropriate.js');
        this.display('square', 'inappropriate', 'INAPPROPRIATE?', $additionalParams);
    },
    directory_browser:function ($additionalParams) {
        loadScript(conf.jsurl + '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(conf.jsurl + '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(conf.jsurl + 'content_display/feedback.js');
        this.display('square', 'feedback', 'FEEDBACK', $additionalParams);
    },
    delete_business:function ($additionalParams) {
    	loadScript(conf.jsurl + '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="'+ conf.imagesurl  +'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(conf.swfurl + "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(conf.swfurl + "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(conf.swfurl + "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(conf.swfurl + "mediaplayer.swf", divID, "320", "240", "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(conf.swfurl +  "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.2 <http://code.google.com/p/swfobject/>
	is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}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 openine a new login window, and then calling a callback function when done
 */
function loginDialog($use){
    var loginWindow = window.open('http://www.yahoo.com','','scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
    setTimeout ( "checkLoginDialog(" + loginWindow + ")", 2000 );

}

function checkLoginDialog(loginWindow){
    if (loginWindow.closed)
    {
        alert('you have closed the window')
    }
    else
    {
        setTimeout ( "checkLoginDialog(" + loginWindow + ")", 2000 );
    }
}


/**
 * 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;
    }
}

/*
	  * Opens a new window, and checks to see if that window is still open every 500 milliseconds
	  * And then calls a callbackfunction when the window is closed.
	  */
	function showDialog($url, $callbackfunc, $title, $windowoptions){
		var loginWindow = window.open($url,$title,$windowoptions);
		setTimeout(function () { checkAShownDialog(loginWindow,$callbackfunc); }, 500)
	}

	function checkAShownDialog(loginWindow,$callbackfunc){
		if (loginWindow.closed)
			$callbackfunc();
		else
			setTimeout(function () { checkAShownDialog(loginWindow,$callbackfunc); }, 500)
	}

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\" rel=\"nofollow\" 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);
    }
}


/**
 * The video Image Box code
 */
function videoImageBoxInit(listingid){
    var videoImageDivClass = "#videoImageBox" + listingid;
    var urlstr = '/libs/JSON/JSON_actions.php?JSON_string=false&type=listing_media&params=[' + listingid + ']&callback=?';

    var arrayBusinessVideos = [];
    var arrayUserVideos = [];
    var arrayBusinessImages = [];
    var arrayUserImages = [];
    var arrayStoreFrontImages = [];
    var arrayScreenGrabs = [];
		
    $.getJSON(urlstr , function(data) {
        if (data.num_images != undefined) {
            if (data.num_images > 0) {
                $.each(data.images, function(key, value) { 
                    if (value.bStoreFrontImageID != undefined) {
                        if (value.bStoreFrontImageID > 0) {
                            if (value.deleted != 1 || value.deleted  == undefined) {
                                arrayStoreFrontImages.push(value);
                            }
                        }
                    } else { 
                        if (value.business_image != undefined) {
                            if (value.business_image == true) {
                                if (value.deleted != 1 || value.deleted  == undefined) {
                                    arrayBusinessImages.push(value);
                                }
                            } else {
                                if (value.link != undefined && value.caption != undefined && value.caption != '' && value.caption.indexOf("Screengrab") > 0) {
                                    if (value.deleted != 1 || value.deleted  == undefined) {
                                        arrayScreenGrabs.push(value);
                                    }
                                } else {
                                    if (value.deleted != 1 || value.deleted  == undefined) {
                                        arrayUserImages.push(value);
                                    }
                                }
                            }
                        } else {
                            if (value.link != undefined && value.caption != undefined && value.caption != '' && value.caption.indexOf("Screengrab") > 0) {
                                if (value.deleted != 1 || value.deleted  == undefined) {
                                    arrayScreenGrabs.push(value);
                                }
                            } else {
                                if (value.deleted != 1 || value.deleted  == undefined) {
                                    arrayUserImages.push(value);
                                }
                            }
                        }
                    }
                });
            }
        }
						
        if (data.num_videos != undefined) {
            if (data.num_videos > 0) {
                $.each(data.videos, function(key, value) { 
                    if (value.business_video != undefined) {
                        if (value.business_video == true) {
                            if (value.deleted != 1 || value.deleted  == undefined) {
                                arrayBusinessVideos.push(value);
                            }
                        } else {
                            if (value.deleted != 1 || value.deleted  == undefined) {
                                arrayUserVideos.push(value);
                            }
                        }
                    } else {
                        if (value.deleted != 1 || value.deleted  == undefined) {
                            arrayUserVideos.push(value);
                        }
                    }
                });
            }
        }
			
        outputHTMLCode = videoImageBoxPrepareStoreFront(arrayStoreFrontImages) + videoImageBoxPrepareVideo(arrayBusinessVideos) + videoImageBoxPrepareVideo(arrayUserVideos) + videoImageBoxPrepareImage(arrayBusinessImages) + videoImageBoxPrepareImage(arrayUserImages) + videoImageBoxPrepareImageGrabber(arrayScreenGrabs);
        if (outputHTMLCode != ''){
            $(videoImageDivClass).html(outputHTMLCode);
            $(videoImageDivClass).find('div:first').toggle();
            $(videoImageDivClass).find('div:first').toggleClass('videoImageBoxImageCurrentlySelected');
            $('#videoImageBoxControlsCounter' + listingid).html("1/" + $(videoImageDivClass).children('div').length);
        } else {
            outputHTMLCode = "<p><h1 style='color:#999;'>NO CONTENT YET</h1><br/><table border='0'><tr>";
            outputHTMLCode = outputHTMLCode + "<td width='107px' style='text-align:center;'><a class=\"blueLink\" onClick=\"popup.add_image(['listing', "+ listingid +"]); return false;\">upload images</a></td>";
            outputHTMLCode = outputHTMLCode + "<td width='107px' style='text-align:center;'><a class=\"blueLink\" onClick=\"popup.add_video(['listing', '"+ listingid +"']); return false;\">upload videos</a></td>";
            outputHTMLCode = outputHTMLCode + "<td width='107px' style='text-align:center;'><a class=\"blueLink\" onClick=\"popup.add_review(['review', '"+ listingid +"']); return false;\">write a review</a></td></tr></table>";
            
            $(videoImageDivClass).html(unescape(outputHTMLCode));
        }
			
        $('#videoImageBoxControlsNext' + listingid).bind('click', function() {
		
            if ( $(videoImageDivClass).find('div:last').hasClass('videoImageBoxImageCurrentlySelected') == false ){
                $(videoImageDivClass).find('.videoImageBoxImageCurrentlySelected').toggleClass('videoImageBoxImageCurrentlySelected').toggle().next('div').fadeIn().toggleClass('videoImageBoxImageCurrentlySelected');
               	   $('#videoImageBoxControlsCounter' + listingid).html(($(videoImageDivClass).find('.videoImageBoxImageCurrentlySelected').index() + 1) + "/" + $(videoImageDivClass).children('div').length);
            }
        });
			
        $('#videoImageBoxControlsPrevious' + listingid).bind('click', function() {
            if ( $(videoImageDivClass).find('div:first').hasClass('videoImageBoxImageCurrentlySelected') == false ){
                $(videoImageDivClass).find('.videoImageBoxImageCurrentlySelected').toggleClass('videoImageBoxImageCurrentlySelected').toggle().prev('div').fadeIn().toggleClass('videoImageBoxImageCurrentlySelected');
				
                //$('videoImageBoxControlsCounter' + listingid).html(  ($(videoImageDivClass).find('.videoImageBoxImageCurrentlySelected').index() + 1) + "/" + $(videoImageDivClass).children('div').length);
               $('#videoImageBoxControlsCounter' + listingid).html(($(videoImageDivClass).find('.videoImageBoxImageCurrentlySelected').index() + 1) + "/" + $(videoImageDivClass).children('div').length);
            }
        });
    });
	
    function videoImageBoxPrepareImage(imageObject){
        var output = '';
        $.each(imageObject, function(key, value) { 
            imageoutput = '';
            if (value.thumb_path != undefined){
                imageoutput = "<div class='videoImageBoxImage' style='display:none;'><a href='/actions.php?type=popup_content&amp;params=[%22square_popup_2%22,%22image_enlarge%22,%22PHOTO GALLERY%22,[%22listing%22,"+ value.type_id +","+ value.image_id +"]]' onclick='popup.image_enlarge([\"listing\","+ value.type_id +","+ value.image_id +"]); return false;'><img class='videoImageBoxImage' title='"+ value.caption +"' alt='"+ value.caption +"' src='" + value.thumb_path.replace("nocrop=1","nocrop=0") + "' border='0'/></a></div>";
            }
            output = output + imageoutput;
        });
        return output;
    }
        
    function videoImageBoxPrepareStoreFront(imageObject){
        var output = '';
        $.each(imageObject, function(key, value) { 
            imageoutput = '';
            if (value.path != undefined){
                imageoutput = "<div class='videoImageBoxImage' style='display:none;'><a href='/actions.php?type=popup_content&amp;params=[%22square_popup_2%22,%22image_enlarge%22,%22PHOTO GALLERY%22,[%22listing%22,"+ value.id +","+ value.bStoreFrontImageID +"]]' onclick='popup.image_enlarge([\"listing\","+ value.id +","+ value.bStoreFrontImageID +"]); return false;'><img class='videoImageBoxImage' src='" + value.path.replace("nocrop=1","nocrop=0") + "' border='0'/></a></div>";
            }
            output = output + imageoutput;
        });
        return output;
    }
    
    function videoImageBoxPrepareImageGrabber(imageObject){
        var output = '';
        $.each(imageObject, function(key, value) { 
            imageoutput = '';
            if (value.thumb_path != undefined){
                imageoutput = "<div class='videoImageBoxImage' style='display:none;'><a href='"+ value.link +"' target='_blank'><img title='"+ value.caption +"' alt='"+ value.caption +"' src='" + value.thumb_path.replace("nocrop=1","nocrop=0") + "' border='0'/></a></div>";
            }
            output = output + imageoutput;
        });
        return output;
    }
	
    function videoImageBoxPrepareVideo(videoObject){
	
        var playbuttonurl = conf.imagesurl + "videoimagebox/videoImageBoxPlayButton.png"
        var output = '';
		
        $.each(videoObject, function(key, value) {
            videooutput = '';
            if (value.thumb_path != undefined){
                videooutput = "<div class='videoImageBoxVideo' style='display:none;background-repeat:no-repeat;width:320px;height:240px;background-image:url("+ value.thumb_path +");height:'><a href='/actions.php?type=popup_content&amp;params=[\"square_popup_2\",\"video_enlarge\",\"VIDEO GALLERY\",[\"listing\","+ value.type_id +","+ value.video_id +", \"listing\", 18755]]' onclick='popup.video_enlarge([\"listing\","+ value.type_id +","+ value.video_id +", \"listing\", "+ value.type_id +"]); return false;'><img title='Video Thumbnail: "+ value.caption +"' alt='Video Thumbnail: "+ value.caption +"' src='" + playbuttonurl + "' border='0'/></a></div>";
            }

            output = output + videooutput;
        });
        return output;
    }
				
}




/**
 * The video Image Box code
 */
function videoImageBoxInitOneItem(listingid){
    var videoImageDivClass = "#videoImageBox" + listingid;
    var urlstr = '/libs/JSON/JSON_actions.php?JSON_string=false&type=listing_media_one_item&params=[' + listingid + ']&callback=?';
    
    var arrayBusinessVideos = [];
    var arrayUserVideos = [];
    var arrayBusinessImages = [];
    var arrayUserImages = [];
    var arrayStoreFrontImages = [];
    var arrayScreenGrabs = [];
    
    var listingLink = '';
		
    $.getJSON(urlstr , function(data) {
        
        if (data.num_images != undefined) {
            if (data.num_images > 0) {
                $.each(data.images, function(key, value) { 
                    if (value.bStoreFrontImageID != undefined) {
                        if (value.bStoreFrontImageID > 0) {
                            if (value.deleted != 1 || value.deleted  == undefined) {
                                arrayStoreFrontImages.push(value);
                            }
                        }
                    } else { 
                        if (value.business_image != undefined) {
                            if (value.business_image == true) {
                                if (value.deleted != 1 || value.deleted  == undefined) {
                                    arrayBusinessImages.push(value);
                                }
                            } else {
                                if (value.link != undefined && value.caption != undefined && value.caption != '' && value.caption.indexOf("Screengrab") > 0) {
                                    if (value.deleted != 1 || value.deleted  == undefined) {
                                        arrayScreenGrabs.push(value);
                                    }
                                } else {
                                    if (value.deleted != 1 || value.deleted  == undefined) {
                                        arrayUserImages.push(value);
                                    }
                                }
                            }
                        } else {
                            if (value.link != undefined && value.caption != undefined && value.caption != '' && value.caption.indexOf("Screengrab") > 0) {
                                if (value.deleted != 1 || value.deleted  == undefined) {
                                    arrayScreenGrabs.push(value);
                                }
                            } else {
                                if (value.deleted != 1 || value.deleted  == undefined) {
                                    arrayUserImages.push(value);
                                }
                            }
                        }
                    }
                });
            }
        }
						
        if (data.num_videos != undefined) {
            if (data.num_videos > 0) {
                $.each(data.videos, function(key, value) { 
                    if (value.business_video != undefined) {
                        if (value.business_video == true) {
                            if (value.deleted != 1 || value.deleted  == undefined) {
                                arrayBusinessVideos.push(value);
                            }
                        } else {
                            if (value.deleted != 1 || value.deleted  == undefined) {
                                arrayUserVideos.push(value);
                            }
                        }
                    } else {
                        if (value.deleted != 1 || value.deleted  == undefined) {
                            arrayUserVideos.push(value);
                        }
                    }
                });
            }
        }
        
        if(arrayStoreFrontImages.length>0) {
            outputHTMLCode = videoImageBoxPrepareStoreFront(arrayStoreFrontImages);
        } else if(arrayBusinessVideos.length>0) {
            outputHTMLCode = videoImageBoxPrepareVideo(arrayBusinessVideos);
        } else if(arrayUserVideos.length>0) {
            outputHTMLCode = videoImageBoxPrepareVideo(arrayUserVideos);
        } else if(arrayBusinessImages.length>0) {
            outputHTMLCode = videoImageBoxPrepareImage(arrayBusinessImages);
        } else if(arrayUserImages.length>0) {
            outputHTMLCode = videoImageBoxPrepareImage(arrayUserImages);
        } else if(arrayScreenGrabs.length>0) {
            outputHTMLCode = videoImageBoxPrepareImageGrabber(arrayScreenGrabs);
        }
//        outputHTMLCode = videoImageBoxPrepareStoreFront(arrayStoreFrontImages) + videoImageBoxPrepareVideo(arrayBusinessVideos) + videoImageBoxPrepareVideo(arrayUserVideos) + videoImageBoxPrepareImage(arrayBusinessImages) + videoImageBoxPrepareImage(arrayUserImages) + videoImageBoxPrepareImageGrabber(arrayScreenGrabs);
        
        if (outputHTMLCode != ''){
            $(videoImageDivClass).html(outputHTMLCode);
            //$(videoImageDivClass).find('div:first').toggle();
            //$(videoImageDivClass).find('div:first').toggleClass('videoImageBoxImageCurrentlySelected');
            //$('#videoImageBoxControlsCounter' + listingid).html("1/" + $(videoImageDivClass).children('div').length);
        } else {
            outputHTMLCode = "<p><h1 style='color:#999;'>NO CONTENT YET</h1><br/><table border='0'><tr>";
            outputHTMLCode = outputHTMLCode + "<td width='107px' style='text-align:center;'><a class=\"blueLink\" href=\"/actions.php?type=popup_content&params=['','add_image','ADD AN IMAGE',['listing',"+ listingid +"]]\" onClick=\"popup.add_image(['listing', "+ listingid +"]); return false;\">upload images</a></td>";
            outputHTMLCode = outputHTMLCode + "<td width='107px' style='text-align:center;'><a class=\"blueLink\" href=\"/actions.php?type=popup_content&params=['','add_video','ADD A VIDEO',['listing',"+ listingid +"]]\" onClick=\"popup.add_video(['listing', '"+ listingid +"']); return false;\">upload videos</a></td>";
            outputHTMLCode = outputHTMLCode + "<td width='107px' style='text-align:center;'><a class=\"blueLink\" href=\"/actions.php?type=popup_content&params=['','add_review','REVIEW THIS BUSINESS',['review',"+ listingid +"]]\" onClick=\"popup.add_review(['review', '"+ listingid +"']); return false;\">write a review</a></td></tr></table>";
            
            $(videoImageDivClass).html(unescape(outputHTMLCode));
        }
			
//        $('#videoImageBoxControlsNext' + listingid).bind('click', function() {
//		
//            if ( $(videoImageDivClass).find('div:last').hasClass('videoImageBoxImageCurrentlySelected') == false ){
//                $(videoImageDivClass).find('.videoImageBoxImageCurrentlySelected').toggleClass('videoImageBoxImageCurrentlySelected').toggle().next('div').fadeIn().toggleClass('videoImageBoxImageCurrentlySelected');
//               	   $('#videoImageBoxControlsCounter' + listingid).html(($(videoImageDivClass).find('.videoImageBoxImageCurrentlySelected').index() + 1) + "/" + $(videoImageDivClass).children('div').length);
//            }
//        });
//			
//        $('#videoImageBoxControlsPrevious' + listingid).bind('click', function() {
//            if ( $(videoImageDivClass).find('div:first').hasClass('videoImageBoxImageCurrentlySelected') == false ){
//                $(videoImageDivClass).find('.videoImageBoxImageCurrentlySelected').toggleClass('videoImageBoxImageCurrentlySelected').toggle().prev('div').fadeIn().toggleClass('videoImageBoxImageCurrentlySelected');
//				
//                //$('videoImageBoxControlsCounter' + listingid).html(  ($(videoImageDivClass).find('.videoImageBoxImageCurrentlySelected').index() + 1) + "/" + $(videoImageDivClass).children('div').length);
//               $('#videoImageBoxControlsCounter' + listingid).html(($(videoImageDivClass).find('.videoImageBoxImageCurrentlySelected').index() + 1) + "/" + $(videoImageDivClass).children('div').length);
//            }
//        });
    });
	
    function videoImageBoxPrepareImage(imageObject){
        var output = '';
        var value=imageObject[0];
        if (value.thumb_path != undefined){
            output = "<div class='videoImageBoxImage'><img class='videoImageBoxImage' title='"+ value.caption +"' alt='"+ value.caption +"' src='" + value.thumb_path.replace("nocrop=1","nocrop=0") + "' border='0'/></div>";
        }
        return output;
    }
        
    function videoImageBoxPrepareStoreFront(imageObject){
        var output = '';
        var value=imageObject[0];
        if (value.path != undefined){
           output = "<div class='videoImageBoxImage'><img class='videoImageBoxImage' src='" + value.path.replace("nocrop=1","nocrop=0") + "' border='0'/></div>";
        }
        return output;
    }
    
    function videoImageBoxPrepareImageGrabber(imageObject){
        var output = '';
        var value=imageObject[0];
        if (value.thumb_path != undefined){
                output = "<div class='videoImageBoxImage'><img title='"+ value.caption +"' alt='"+ value.caption +"' src='" + value.thumb_path.replace("nocrop=1","nocrop=0") + "' border='0'/></div>";
            }
        return output;
    }
	
    function videoImageBoxPrepareVideo(videoObject){
	
        var playbuttonurl = "/images/videoimagebox/videoImageBoxPlayButton.png"
        var output = '';
        var value=videoObject[0];
        if (value.thumb_path != undefined){
                output = "<div class='videoImageBoxVideo'><img title='Video Thumbnail: "+ value.caption +"' alt='Video Thumbnail: "+ value.caption +"' src='" + value.thumb_path + "' border='0'/></div>";
            }
        return output;
    }
				
}
