var lastDmaId = 0;
function addslashes(str){
    return str.replace('\'','\\\'').replace('\"','\\\"');
}

function htmlquotes(str){
    return str.replace('\'','&apos;').replace('\"','&quot;');
}

var nearbyMarkers = new Array();
var nearbyMarkersMore = new Array();
function showHideOklaTravel() {
    if ($('oklatravel_video').style.display == 'none') {
        $('oklatravel_video').style.display = 'block';
    } else {
        $('oklatravel_video').style.display = 'none';
    }
}
function toggleOklatravel() {
    if ($('oklatravel_video').style.display == 'block') {
        Effect.toggle('evergreen_video','slide', {beforeStart: showHideOklaTravel});
    } else {
        Effect.toggle('evergreen_video','slide', {afterFinish: showHideOklaTravel});
    }
    if ($('videoButton').src == 'http://static.newsok.biz/sites/wimgo/images/play_video.gif') {
        $('videoButton').src = 'http://static.newsok.biz/sites/wimgo/images/close_video.gif';
    } else {   
        $('videoButton').src = 'http://static.newsok.biz/sites/wimgo/images/play_video.gif';
    }
}
function showHideStreetView() {
    if ($('street_view').style.display == 'none') {
        $('street_view').style.display = 'block';
    } else {
        $('street_view').style.display = 'none';
    }
}
function toggleStreetView(i) {
    if ($('street_view').style.display == 'block') {
        Effect.toggle('street_view_holder_content','slide', {beforeStart: showHideStreetView});
    } else {
        Effect.toggle('street_view_holder_content','slide', {afterFinish: showHideStreetView});
    }
    $(i+'_toggle').className=($(i+'_toggle').className == 'togglePlus')? "toggleMinus":"togglePlus";
}
function showHideItems(i) {
    try {
        $(i+'_toggle').className=($(i+'_toggle').className == 'togglePlus')? "toggleMinus":"togglePlus";
        Effect.toggle(i+'_content','slide',{duration:0.5});
    } catch (e) { }
}
function toggleMapLarge(i, x, y, z, w) {
    new Effect.Morph(x,{style:'height:0', duration:0.5});
    new Effect.Morph(i,{style:'width:571px; height: 439px; right:345px', duration:0.5});
    Effect.Fade(y,{duration:0.5});
    Effect.Appear((z), {queue: 'end', duration:0.5});
    new Effect.Morph(w,{style:'height:408px', duration:0.5, afterFinish: function() {mapper.checkResize();}});
}
function toggleMapSmall(i, x, y, z, w) {
    new Effect.Morph(x,{style:'height:350px', duration:0.5});
    new Effect.Morph(i,{style:'width:296px; height: 315px; right:0px', duration:0.5});
    Effect.Fade(z, {duration:0.5});
    Effect.Appear((y), {queue: 'end', duration:0.5});
    new Effect.Morph(w,{style:'height:285px', duration:0.5, afterFinish: function(){mapper.checkResize();}});
}
function toggleMovieLarge(i, x, y, z, w) {
    new Effect.Morph(x,{style:'height:0', duration:0.5});
    new Effect.Morph(i,{style:'width:571px; height: 439px; right:345px', duration:0.5});
    Effect.Fade(y,{duration:0.5});
    Effect.Appear((z), {queue: 'end', duration:0.5});
    new Effect.Morph(w,{style:'height:408px', duration:0.5});
}
function toggleMovieSmall(i, x, y, z, w) {
    new Effect.Morph(x,{style:'height:310px', duration:0.5});
    new Effect.Morph(i,{style:'width:296px; height: 285px; right:0px', duration:0.5});
    Effect.Fade(z, {duration:0.5});
    Effect.Appear((y), {queue: 'end', duration:0.5});
    new Effect.Morph(w,{style:'height:255px', duration:0.5});
}
function fadeToggle(i) {
    try {
        Effect.toggle(i, 'appear',{duration:0.5});
    } catch (e) { }
}
function slideToggle(i) {
    try {
        if(typeof i == 'string') i = document.getElementById(i); 
        i.style.display = (i.style.display == 'none') ? 'block' : 'none';
    } catch (e) { }
}
var footerState = 'closed';
function footerAppear(footer, content, content_text, content_header) {
    try {
        $('content_about').style.display = 'none';
        $('content_faq').style.display = 'none';
        $('content_whatis').style.display = 'none';
        $('content_opubco').style.display = 'none';
        $('header_about').style.display = 'none';
        $('header_faq').style.display = 'none';
        $('header_whatis').style.display = 'none';
        $('header_opubco').style.display = 'none';
        $(content_text).style.display = 'block';
        $(content_header).style.display = 'block';
        if (footerState == 'closed') {
            Effect.SlideDown(footer, {queue:'front', duration:0.5});
            Effect.Appear(content, {queue:'end', duration:0.5});
            footerState = 'opened';
        }
    } catch (e) { }
}
function footerClose() {
    Effect.SlideUp('footer_expand', {queue:'end', duration:0.5});
    Effect.Fade('footer_appear', {queue:'front', duration:0.5});
    footerState = 'closed';
}

function toggleText(i, x, y) {
    if (document.getElementById(i).innerHTML == x) {
        document.getElementById(i).innerHTML = y;
    } else {
        document.getElementById(i).innerHTML = x;
    }
}
function clearText(inputBox, clearText){
    if(inputBox.value == clearText){
        inputBox.value = '';
    }else{
        inputBox.select();
    }
}
function divSwap(element){
   var div = document.getElementById('tab_content');
   var nodeList = div.childNodes;
   var queue = Effect.Queues.get('menuScope');

   if(queue.toArray().length<1){
        if(Element.visible(element)==false){
            for(i=0;i<nodeList.length;i++){
                if(nodeList.item(i).nodeName=="DIV" && nodeList.item(i).id!=element){
                    if(Element.visible(nodeList.item(i))==true){
                        $(nodeList.item(i)).style.display="none";
                    }
                }
            }
            $(element).style.display="block";
        }
   }
}

function profileSwap(element){
   var div = document.getElementById('profile_content');
   var nodeList = div.childNodes;
   var queue = Effect.Queues.get('menuScope');

   if(queue.toArray().length<1){
        if(Element.visible(element)==false){
            for(i=0;i<nodeList.length;i++){
                if(nodeList.item(i).nodeName=="DIV" && nodeList.item(i).id!=element){
                    if(Element.visible(nodeList.item(i))==true){
                        Effect.Fade(nodeList.item(i),{queue:{position:'front',scope:'menuScope',limit:2},duration:0.5})
                    }
                }
            }
            Effect.Appear(element,{queue:{position:'end',scope:'menuScope',limit:2},duration:0.5})
       }
   }
    myProfileTab.className='notSelected';
    myAlertsTab.className='notSelected';
    myWidgetsTab.className='notSelected';
    myCoolTab.className='notSelected';
    $(element+'Tab').className=($(element+'Tab').className == 'selected')? "notSelected":"selected";
}

function getElementsByClassName(classname, node) {
      if(!node) node = document.getElementsByTagName("body")[0];
      var a = [];
      var re = new RegExp('\\b' + classname + '\\b');
      var els = node.getElementsByTagName("*");
      for(var i=0,j=els.length; i<j; i++)
      if(re.test(els[i].className))a.push(els[i]);
      return a;
}

function toggleNearby()
{
    for(i=0; i<nearbyMarkersMore.length; i++){
        
        if(document.getElementById('viewMore_nearby').style.display.replace(" ", "") != 'none'){
            mapper.removeOverlay(nearbyMarkersMore[i]);
        }else{
            mapper.addOverlay(nearbyMarkersMore[i]);
        }
    }
    slideToggle('viewMore_nearby');
    slideToggle('nearbyPagination');
    toggleText('viewMore_nearby_text', 'See more...', 'See less...');
}

function getNearby(venue_id, lat, lon, cat, page, dmaId)
{
    if (typeof(dmaId) == "undefined") {
        dmaId = lastDmaId;
    }
    page = page || 1;
    var url = "/api";
    var qstring = "method=Nearby.Nearby&callback=displayNearby&venue_id="+venue_id+"&lat="+lat+"&lon="+lon+"&cat="+cat+"&page="+page+"&dmaId="+dmaId;
    loadJSON(url, qstring);
}

function displayNearby(nearbyReturn)
{
    var j = 0;

    clearPoints();
    nearbyMarkers = new Array();
    nearbyMarkersMore = new Array();
    
    if (nearbyReturn != null) {
    var nearby = nearbyReturn.nearby;
    var featured_nearby = nearbyReturn.featured_nearby;
    var venue_id = nearbyReturn.venue_id;
    var lat = nearbyReturn.lat;
    var lon = nearbyReturn.lon;
    var cat = nearbyReturn.cat_selected;
    var page = nearbyReturn.page;

    var count = nearbyReturn.count;
    var lim = nearbyReturn.limit;
    var pages = Math.floor(count/lim);

    var nextPage = ((Number(page)+1) <= pages)? (Number(page)+1):1;
    var prevPage = ((page-1) < 1)?pages:Number(page)-1;
  
    if(nearby.length >5) {
        j = 5;
    } else {
        j = nearby.length;
    }
    var hidden = true;


    if(typeof(viewMoreNearbyAlways) == 'undefined') viewMoreNearbyAlways = false;

    var viewMore_nearby = document.getElementById('viewMore_nearby');
    if (viewMore_nearby && !viewMoreNearbyAlways) {
            hidden = (viewMore_nearby.style.display == 'none') ? true : false;
    }
    if(viewMoreNearbyAlways){
            hidden = false;
    }

    var divList = "";
    divList  = "<div id='top_nearby_contain' class='list_padding'>";
    divList += "<ul>";
    for(i=0; i<j; i++)
    {
        divList += "<li id='map_"+nearby[i].id+"'>";
        divList += "<a target='_parent' href='/"+nearby[i].clean_title+"/business/"+nearby[i].id+"'>";
        divList += "<div class='nearby_sdistance_element'>" + nearby[i].distance + " miles</div>";
        divList += "<div class='nearby_title_element'>"+nearby[i].title+"</div>";
        divList += "</a>";
        divList += "</li>";
    }
    divList += "</ul>";
    divList += "</div>";
    nearbyDiv = document.getElementById('nearby');
    nearbyDiv.innerHTML = divList;


    if(nearbyReturn.page > 1){
        addToMap = true;
        navText = 'See less...';
     }else{
        addToMap = false;
        navText = 'See more...';
    }

    if(j >= 5){
        divListBottom  = "<div id='viewMore_nearby' style='"+ (hidden ? "display:none;" : "") +"'>";
        divListBottom += "<ul>";
        for(i=j; i<nearby.length; i++)
        {
            divListBottom += "<li id='map_"+nearby[i].id+"'>";
            divListBottom += "<a target='_parent' href='/"+nearby[i].clean_title+"/business/"+nearby[i].id+"'>";
            divListBottom += "<div class='nearby_sdistance_element'>" + nearby[i].distance + " miles</div>";
            divListBottom += "<div class='nearby_title_element'>"+nearby[i].title+"</div>";
            divListBottom += "</a>";
            divListBottom += "</li>";

        }
        divListBottom += "</ul>";
        divListBottom += "</div>";
        nearbyDiv.innerHTML += divListBottom;

       //» «
        var prev = 'getNearby('+ venue_id +',' +lat+',' +lon+',' +cat+',' +prevPage+')';
        var next = 'getNearby('+ venue_id +',' +lat+',' +lon+',' +cat+',' +nextPage+')';
        var count= ' ' + page + ' of ' + pages + ' '; 
        var nodePrev = "<a id='nearbyPrev' href='javascript:void(0);' onclick='"+prev+"'>Prev</a>";
        var nodeCount = "<span>"+count+"</span>";
        var nodeNext = "<a id='nearbyNext' href='javascript:void(0);' onclick='"+next+"'>Next</a>";

        var ulPrevNext = "<ul id='nearbyPagination' class='pages' style='padding:10px 0 5px 0; "+ (hidden ? "display:none;" : "") +"'>";
        ulPrevNext += "<li class='pageBtn'>"+nodePrev+"<li>";
        ulPrevNext += "<li class='pageCount'>"+nodeCount+"<li>";
        ulPrevNext += "<li class='pageBtn'>"+nodeNext+"<li>";
        ulPrevNext += "</ul>";

        nearbyDiv.innerHTML += ulPrevNext;
        
        var divMoreNearby = "<div id='viewMore_nearby_link' class='imgoing_more' "+ (viewMoreNearbyAlways ? "style='display:none;'":"") +">";
        divMoreNearby += "<a href='javascript:void(0);' onclick='toggleNearby();'>";
        divMoreNearby += "<span id='viewMore_nearby_text'>"+navText+"</span";
        divMoreNearby += "</a>";
        divMoreNearby += "</div>";
        divMoreNearby += "<div class='clear'></div>";
        nearbyDiv.innerHTML += divMoreNearby;

    }

    if( window.gm !== undefined ){
        window.gm.clear(1);
        window.gm.populate(nearby);
    } 

    //if (document.getElementById('map')) {

    //for(i=0; i<j; i++)
    //{
    //    li = document.getElementById('nearby_'+nearby[i].id);
    //    nearbyMarkers.push(addPoint(nearby[i], li,true ,'http://static.newsok.biz/sites/wimgo/images/mapicon2_o_' + nearby[i].cat_id + '.png', true));
    //}
    //if(j >= 5){
    //    for(i=j; i<nearby.length; i++)
    //    {
    //        li = document.getElementById('nearby_'+nearby[i].id);
    //        nearbyMarkersMore.push(addPoint(nearby[i], li,true ,'http://static.newsok.biz/sites/wimgo/images/mapicon2_o_' + nearby[i].cat_id + '.png', true));
    //    }
    //}

    //}
    } else {
        nearbyDiv.innerHTML = "Sorry no listings available.";
    }
}

function givePref(profile_id, pref_id, module_id, module_type_id){
    if(!eProfile.isAuth()){
        alert('Please sign in to wimgo.');
        ShadeManager.showForm('login'); 
        trackClick('Shade - Sign In');
        return true;
    }
    if(!pref_id){
        alert('Error: Please provide a preference id');
        return false;
    }
    if(!module_id){
        alert('Error: Please provide a module id');
        return false;
    }
    if(!module_type_id){
        alert('Error: Please provide a module type id');
        return false;
    }

    var url = "/ajax/okla365/pref.php";
    params  = "profile_id="+escape(profile_id)+"&pref_id="+escape(pref_id)+"&module_id="+escape(module_id)+"&module_type_id="+escape(module_type_id);
    new Ajax.Request(url, { method:'get', parameters: params, onSuccess: function(transport) { doJSON(transport); }});
}
function prefGiven(data){
    if(data.success == 1){
        for(i=0; i<data.prefs.length; i++){
            $('pref_count_'+data.prefs[i].pref_id).innerHTML = data.prefs[i].pref_count;
            $('pref_'+data.prefs[i].pref_id).addClassName('imgoing_button');
            $('pref_'+data.prefs[i].pref_id).removeClassName('imgoing_button_selected');
        }
        $('pref_'+data.pref).addClassName('imgoing_button_selected');
    }else{
        $('pref_msg').innerHTML = "A problem was encoutered.";
    }
}
function getPref(module_id, module_type_id){
    if(!eProfile.isAuth()){
        return true;
    }
    if(!module_id){
        alert('Error: Please provide a module id');
        return false;
    }
    if(!module_type_id){
        alert('Error: Please provide a module type id');
        return false;
    }

    var url = "/ajax/okla365/pref.php";
    params  = "option=get_pref&module_id="+escape(module_id)+"&module_type_id="+escape(module_type_id);
    new Ajax.Request(url, { method:'get', parameters: params, onSuccess: function(transport) { doJSON(transport); }});
}
function prefGotten(data){
    if(data.success == 1){
        $('pref_'+data.pref).addClassName('imgoing_button_selected');
    }
}
function deleteItem(module_id, module_type_id){
/*
    if(!eProfile.isAuth()){
        alert('Sorry, you do not have permission to delete this item.');
        return true;
    }
*/
    if(!module_id){
        alert('Error: Please provide a module id');
        return false;
    }
    if(!module_type_id){
        alert('Error: Please provide a module type id');
        return false;
    }

    var okay = confirm("Are you sure you want to delete this item?\n\nWARNING: IF YOU DELETE THIS ITEM IT WILL BE PERMANENT, THERE IS NO GOING BACK!");
    if(okay){
        var url = "/ajax/okla365/delete.php";
        params  = "module_id="+escape(module_id)+"&module_type_id="+escape(module_type_id);
        new Ajax.Request(url, { method:'get', parameters: params, onSuccess: function(transport) { doJSON(transport); }});
    }
}
function itemDeleted(data){
    if(data.success == 1){
        window.location.href="/";
    }else{
        alert(data.msg);
    }

}
function invite_friend(tf_url){
    var email = $('tf_email').value;
    var message = $('tf_message').value;
    var url = "/ajax/okla365/invite_friend.php?email="+email+"&message="+message+"&url="+tf_url;
    new Ajax.Request(url, { method:'get', onSuccess: function(transport) { doJSON(transport); }});
}
function invited_friends(data){
    if(data.success == 1){
        $('tf_msg').innerHTML = "Email sent.";
       new Effect.Highlight('tf_msg', {queue:'front',startcolor:'#ff99ff', endcolor:'#999999'})
       Effect.Fade('tf_msg',{queue:'end',duration:'.7'});
    }else{
        $('tf_msg').innerHTML = "A problem was encoutered sending email.";
    }
}
function getDirections(start,end){
    //new Ajax.Request('/ajax/okla365/directions.php?start='+escape(start)+"&end="+escape(end));
    url = 'http://maps.google.com/maps?f=d&hl=en&geocode=&time=&date=&ttype=&saddr='+escape(start)+'&daddr='+escape(end)+'&sspn=0.276491,0.752563&ie=UTF8&z=9&om=1';
    window.open(url,'directions','toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');
}
function toggleMoreEvents(){
    slideToggle('viewMore_upcoming');
    toggleText('viewMore_upcoming_text', 'See more...', 'See less...');
}
function print_friendly(event, item){
    console.log(item.title);
}
function changeRelatedTab(tabID) {
    document.getElementById('comments_tab').className = "notselected";
    document.getElementById('videos_tab').className = "notselected";
    document.getElementById('photos_tab').className = "notselected";
    document.getElementById('news_tab').className = "notselected";
    document.getElementById(tabID).className = "selected";
    if(tabID != 'videos_tab') unLoadVideoBar();
}
function changeSuperTab(tabID) {
    document.getElementById('comments_tab').className = "notselected";
    document.getElementById('videos_tab').className = "notselected";
    document.getElementById('photos_tab').className = "notselected";
    document.getElementById('news_tab').className = "notselected";
    document.getElementById(tabID).className = "selected";
}
var searchText = 'Type your search here.';
function clearSearchText(srchBox) {
    if (srchBox.value == searchText) {
        srchBox.value = "";
    } else {
        srchBox.select();
    }
}
/**
 * Manages the Notify Us form on the details page
 */
AmissForm = {
    initialized:false,
    
    initialize:function()
    {
        if(this.initialized) return;
        this.initialized = true;
        
        this.type_id = $('module_type_id').value;
        this.module_id = $('module_id').value;
        this.form = $("amissForm");
        this.reason = $('amiss_text');
        this.msg = $('amissMsg');
    },
    
    /**
    *   Shows the form in the specified node.
    *   @param HTMLElement  anchor  The anchor tag that was clicked to open the form. 
    *   @param string target    The id of the node that will contain the report form.
    *   @param int    typeid    The module id of the comment.  (FYI Comments are "3")
    *   @param string cid       The  id of the comment being reported.
    */
    show:function()
    {    
        this.initialize();
        new Effect.toggle(this.form, 'slide', {duration:1, queue:'end'});

    },
    
    /**
    *   resets the form fields
    */
    reset:function()
    {
        //clear the form to defaults.
        this.reason.value = '';
    },

    /**
    *   Attempts to send the report.
    *   Expects to find hidden form fields with the module's id and module's type.
    */
    submit:function()
    {
        if(this.reason.value.length == 0) return;
        
        var msg = "We appreciate you letting us know about your concern.  We will review your report and take the appropriate action.  Please be aware that circumstances may prevent us from taking immediate action.";
        this.msg.innerHTML = msg;
        
        //code to send report
        var url = '/ajax/requestJSON.php?';
        url+="method=Objection.AddObjection";
        
        url+="&module_type_id="+this.type_id;
        url+="&module_id="+this.module_id;
        url+="&reason="+escape(escape(this.reason.value));

        this.loadJSON(url);
        this.reset();
        this.show();
    },

    /**
    *  Creates a new script node in the HEAD pointing to a php file that will process the url's 
    *  query string params and return a JSON result.
    *
    *  @param string url A url to the php page that will produce the required javascript code.
    */
    loadJSON:function(url)
    {
       try{
            var headID = document.getElementsByTagName("head")[0];         
            var newScript = document.createElement('script');
            newScript.type = 'text/javascript';
            newScript.src = url;
            headID.appendChild(newScript);
         } catch(e){
            alert("error " + e.message);
         }
    }
}
function toggleDiv() {
    for(i=0,c=arguments.length;i<c;i++){
        var theDiv = document.getElementById(arguments[i]);
        if(typeof theDiv == 'object')
            theDiv.style.display = (theDiv.style.display != 'none' ? 'none' : '' );
    }
}

function toggleInnerHTML(elem,one,two){
    if(elem.innerHTML == one){
        elem.innerHTML = two;
    } else {
        elem.innerHTML = one;
    }
}

function toggleReplies(id) {
    var me = document.getElementById(id);
    me.className = (me.className != "repliesButton open" ? "repliesButton open" : "repliesButton");
}
function clearInput(id) {
    if (document.getElementById(id).value == "Add Tags") {
        document.getElementById(id).value = "";   
    }
}
function toggleObject(id) {
    var el = document.getElementById('objectionReason_'+id);
    el.style.display = (el.style.display != 'none' ? 'none' : '' );
}
function clearReason(id) {
    if (document.getElementById('reason_'+id).value == "Please tell us what is objectionable.") {
        document.getElementById('reason_'+id).value = "";
    }
}
function loadConnectokJSON(url, queryString, type)
{
        var headId = document.getElementsByTagName("head")[0];
        if (typeof(type) == "undefined") type = 'script';


        url += (url.indexOf('?') >= 0) ? "&" : "?";
        url += "noCacheIE=" + (new Date()).getTime() + "&" + queryString;

        if (type == 'link') {
            var link = document.createElement('link');
            link.rel = 'alternate';
            link.type = 'application/rss+xml';
            link.href = url;
        } else {
            var link = document.createElement('script');
            link.type = 'text/javascript';
            link.src = url;
        }
        headId.appendChild(link);
}

function connectokMakeObjection(c_id, reason)
    {
        var c_id = c_id;
        url = apiUrl+"json";
        queryString  = "method=Objection.MakeObjection";
        queryString += "&callback=connectokObjectionMade";
        queryString += "&uid="      + "Comment_" + c_id;
        queryString += "&reason="   + encodeURIComponent(reason);
        loadConnectokJSON(url,queryString,'script');
    }
function connectokObjectionMade(data)
{
        document.getElementById(data.result.uid+'_object').innerHTML = "<span style='color: #A02C2C;'><b>Your objection has been sent.</b></span>";
}   

