/* --- jquery.functions.js --- */
(function($) {

    $(document).ready( function() {
        
        // open link in new tab
        $('a[rel="external"]').click(function() {
            $(this).attr('target','_blank');
        });

        // support for ie
        if ($.browser.msie && $.browser.version.substr(0,1) < 9) { // target IE 8 and below
            // replace all hr tags width divs
            $('hr').each(function() {
                    $(this).replaceWith('<div class="' +$(this).attr('class')+ ' hr" ></div>');
            });

            // h2 span text-indent fix
            $('h2 span').addClass('f-left').parent().addClass('clearfix');
            
            // fake placeholder for IE
            $('#admin-login-form input, .form.mini input[type="text"], .filters input[type="text"]').each(function() {

                var attr = $(this).attr('title');
                if (typeof attr !== 'undefined' && attr !== false) {

                   $(this).val($(this).attr('title')).addClass('placeholder');

                    $(this).focus(function(){
                        if ($(this).val() == $(this).attr('title')) {
                            $(this).val('').removeClass('placeholder');
                        }
                    }).blur(function(){
                        if ($(this).val() == '') {
                            $(this).val($(this).attr('title')).addClass('placeholder');
                        }
                    });

                }
                
            });

        }

        // support for admon console top nav
        if ($('.admin-nav').length > 0) {
            // support for admin subnav
            $('.admin-nav li').hover(function() {
                $(this).addClass('hover');
                $('ul:first',this).animate({opacity: "toggle"}, 300);
            }, function(){
                $(this).removeClass('hover');
                $('ul:first',this).animate({
                    opacity: 'toggle'
                }, 300); // $('ul:first',this).css('visibility', 'hidden');
            });
            $('.admin-nav li:has(ul)').find("a:first").append(' &raquo; ');
            $('.admin-subnav').each(function() {
                var theMinWidth = $(this).parent().width();
                $(this).css('min-width', theMinWidth);
            });
            $('.admin-subnav li:last-child').addClass('last');
        }
        
        // admin console list manipulation
        $('.group ul li:nth-child(even), .listings li:nth-child(even), .s3browser.profile tr:nth-child(even), .dash-select option:nth-child(even)').addClass('even');
        $('.itiration p:odd').addClass('last');

        // regions - show inactive widgets
        $('.inactive-w').click(function() {
            if (!$(this).hasClass('current')) {
                toggleShowInactiveWidgets();
            }
            return false;
        });

        // regions - assign regions graphics
        $('.regions li.region').each(function() {
            var thereg = $(this).attr('id').split('-').pop();
            if (thereg >=1 && thereg <=6) {
                $(this).prepend('<img src="http://s3.amazonaws.com/content.newsok.com/newsok/images/Regions/region'+thereg+'.png" alt="" class="region_locator" />');
            }
        });

        // section - tab
        $('a.tab').click(function() {
            $('a.tab').removeClass('current');
            $(this).addClass('current');
        });

        // section - alpha menu
        $('#allSections .list li a').click(function() {
            $('#allSections li a').removeClass('current');
            $(this).addClass('current');

            $('.sections-listings li').hide()

            var activeClass = 'item-'+this.innerHTML;
            if (activeClass == 'item-0-9') {
                var arr = ['item-0', 'item-1', 'item-2', 'item-3', 'item-4', 'item-5', 'item-6', 'item-7', 'item-8', 'item-9'];
                $.each(arr, function(index, value) {
                   $('.sections-listings li.'+value).show();
                });
            } else {
                $('.sections-listings li.'+activeClass).show();
            }
            return false;
        });

        // section - display search results
        var urlparamsSection = '?findSection=', urlparamsBlocks = '?findBlock=', urlparamsKeywords = '?findKeyword='; 
        if (document.URL.indexOf(urlparamsSection) > 0 || document.URL.indexOf(urlparamsBlocks) > 0 || document.URL.indexOf(urlparamsKeywords) > 0 ) {
            $('.sections-listings li, .clear-search').show();
        }

        // video associsations
        if (document.URL.indexOf('video-assoc')) {
            if ($('.listings li').length > 0 ) {
                $('.centered').show();
            } 
        }
        
        // vendor feed - articles
        $('.modal').click(function() {
            if ($('.dialog').length <= 0) {
                $('header').after('<div class="dialog" style="display:none;"><div class="the-preview"></div></div>');
            }
            var theUrl = 'http://'+document.domain+$(this).attr('href');
            var titre = $(this).closest('tr').find('h2 a').text();
            var theTitle = titre.replace(/Cancel/g,'');
            $('.dialog').dialog({
                    modal:true,
                    width:744,
                    resizable:false,
                    draggable:false,
                    //title: theTitle,
                    open: function() {
                        $(this).find('.the-preview').load(theUrl);
                        $('.ui-dialog-title').text(theTitle);
                    }
            });
            return false;
        });

        // close dialog
        $('.ui-widget-overlay, .close-btn').live('click', function() {
            $('.ui-dialog-content').dialog('close');
            return false;
        });

        // audio, docs - toogle advanced search
        $('#optionsText').click(function() {
            if ($('#advancedOptions').is(':hidden')) {
                $('#advancedOptions').show();
                $('#optionz-wrapper').css('width', '1150px');
                $(this).find('strong').text('Default');
            } else {
                $('#advancedOptions').hide();
                $('#optionz-wrapper').removeAttr('style');
                $(this).find('strong').text('Advanced');
            }
        });

        // audio - no summary? hide link
        $('.the-summary.thesummary').each(function() {
            var sumText = $.trim($(this).text());
            if (sumText == '') {
                $(this).closest('td').next().find('a').hide();
            } 
        });

    });

})(jQuery);

// create galley alert
function confirmCreateGallery() {
    if (confirm('This will create a live gallery on NewsOK.com. Do you want to continue?')) {
      location.href = "http://newsok.com/photos/createGallery";
    }
}

// section -- toggle author info
function toggleAuthorInfo(checkbox) {
    if (checkbox == true) {
        document.getElementById('authorInfo').style.display = "";
    } else {
        document.getElementById('authorInfo').style.display = "none";
    }
}

// vendor feed - articles
function saveChanges(propertyId, value) {
    var params = propertyId + "=" + escape(value);
    if (document.getElementById('isvendorfeeds') != null ) { // on page vendor feed articles
        $.ajax({
            url: "/vendorFeed/articleJson/?"+params
        });
    } else {
        $.ajax({
            url: "/article/list/json/?"+params
        });
    }
}
function saveStatus(propertyId, value) {
    var params = propertyId + "=" + escape(value);
    $.ajax({
        url: "/article/list/json/?"+params
    });
}
function cancelField(id, field) {
    document.getElementById("div_"+field+"_"+id).style.display="none";
    document.getElementById("a_"+field+"_"+id).style.display="block";
}
function editField(id, field, allSections) {
    document.getElementById("div_"+field+"_"+id).style.display="block";
    document.getElementById("a_"+field+"_"+id).style.display="none";
    document.getElementById("input_"+field+"_"+id).value = document.getElementById("a_"+field+"_"+id).innerHTML;

    //JSON Section drop down list 
    var availableTags = allSections; 
    function split( val ) {
        return val.split( /,\s*/ );
    }
    function extractLast( term ) {
        return split( term ).pop();
    }

    $( "#input_"+field+"_"+id )
        // don't navigate away from the field on tab when selecting an item
        .bind( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB &&
                    $( this ).data( "autocomplete" ).menu.active ) {
                event.preventDefault();
            }
        })
        .autocomplete({
            minLength: 0,
            source: function( request, response ) {
                // delegate back to autocomplete, but extract the last term
                response( $.ui.autocomplete.filter(
                    availableTags, extractLast( request.term ) ) );
            },
            focus: function() {
                // prevent value inserted on focus
                return false;
            },
            select: function( event, ui ) {
                var terms = split( this.value );
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push( ui.item.value );
                // add placeholder to get the comma-and-space at the end
                terms.push( "" );
                this.value = terms.join( ", " );
                return false;
            }
        });
        //END JSON Section drop down list
}
function saveField(id, field) {
    saveChanges(document.getElementById("input_"+field+"_"+id).name, document.getElementById("input_"+field+"_"+id).value)
    document.getElementById("a_"+field+"_"+id).innerHTML = document.getElementById("input_"+field+"_"+id).value
    cancelField(id, field);
}
function onEnter(oEvent) {
    if (oEvent.keyCode)
        iAscii = oEvent.keyCode;
    else if (oEvent.which)
        iAscii = oEvent.which;
    else
    return false;
    if (iAscii == 13) return true;
    return false;
}
function copy(inElement) {
  if (inElement.createTextRange) {
    var range = inElement.createTextRange();
    if (range && BodyLoaded==1)
      range.execCommand('Copy');
  } else {
    var flashcopier = 'flashcopier';
    if(!document.getElementById(flashcopier)) {
      var divholder = document.createElement('div');
      divholder.id = flashcopier;
      document.body.appendChild(divholder);
    }
    document.getElementById(flashcopier).innerHTML = '';
    var divinfo = '<embed src="http://static.newsok.biz/sites/newsok7/flash/_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(inElement)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashcopier).innerHTML = divinfo;
  }
}

/* activeImage is Used to verify which image is active n the changeActive function*/ 
function changeActive(id) { 
/*
    var activeImage     = "http://static.newsok.biz/sites/newsok7/images/admin_icons/active.gif";  
    var inActiveImage   = "http://static.newsok.biz/sites/newsok7/images/admin_icons/inactive.gif";  
    var myImg = document.getElementById('img_'+id); 
    if (myImg.src == activeImage) { 
        myImg.src = inActiveImage; 
        saveChanges("approved_"+id, 0); 
    } else { 
        myImg.src = activeImage; 
        saveChanges("approved_"+id, 1); 
    } 
*/
    var statusbtn = document.getElementById('btn_'+id); 

    if (document.getElementById('isvendorfeeds') != null ) { // on page vendor feed articles
        if (statusbtn.className == 'activebtn centered') {
            statusbtn.setAttribute('class', 'inactivebtn centered');
            saveChanges("approved_"+id, 0);
        } else {
            statusbtn.setAttribute('class', 'activebtn centered');
            saveChanges("approved_"+id, 1);
        }
    } else { // on page articles list
        if (statusbtn.className == 'activebtn centered') {
            statusbtn.setAttribute('class', 'inactivebtn centered');
            saveStatus("approved_"+id, 0);
        } else {
            statusbtn.setAttribute('class', 'activebtn centered');
            saveStatus("approved_"+id, 1);
        }
    }
}

function toggleBlock(id) {
    myDiv = document.getElementById(id);
    if (myDiv) myDiv.style.display = (myDiv.style.display == '')?"none":"";
}
