/*  News Page Javascript */

var rowID;
var vidID;
var classnamer;
var classindex;
var first_fire_top = 0;
var first_fire_type = 0;
//var shareID;

// ROW RESETTER  ////////////////////////////////////////////////////////
function rowReset() {
    $$('li.nsDataRow').each(function(s) { 
            var wrap = $$$(s).down('div.nsRowWrap');
            
            if (s.hasClassName('expRow') == true){  
                var rowid = $$$(s).identify();
                var vidid = rowid.replace(/detail-item-/, "ddlCVP");
                var vid_obj = $$$(vidid).down('object');
                if(vid_obj) {
	                var objid = vid_obj.identify();
	                if(CVP.findInstance(objid)) {
	               	   CVP.findInstance(objid).pause();
	                }
                }
                
               new Effect.Scale(s, 31.5, {
                       transition: Effect.Transitions.sinoidal, 
                       scaleX: false,
                       scaleContent: false,
                       scaleFromCenter: true,
                       duration: 0.3, 
                      // queue: {position: 'front',  scope: 'collapseRow'},
                       scaleMode: {originalHeight: 190, originalWidth: 858}
               });
               
               new Effect.Opacity(wrap, { 
                       duration: 0.2,
                       transition: Effect.Transitions.sinoidal,
                       //queue: {position: 'end',  scope: 'collapseRow'},
                       from: 1,
                       to: 0
               });
               s.down('span.nsVideo').setStyle({display: 'none'});

               var fadeReset = function(){
                    new Effect.Opacity(wrap, { 
                       duration: 0.2,
                       transition: Effect.Transitions.sinoidal,
                       queue: 'end',
                       from: 0,
                       to: 1
                    });
                    s.removeClassName('expRow');
                    s.down('span.nsToggler').innerHTML = "<img class='hidearrow' src='http://ddl-turkey.net/templates/ddl/images/content/show.details.arrow.gif' />show details";                   
                    //rowNum = s.identify();
                }
                window.setTimeout(fadeReset, 310);
            } else {
                //console.log(s.classNames);
            }
            //ddlHideOverlay(shareID)
    });
}
// EXPANDED ROW TOGGLER ////////////////////////////////////////////////////////
function expToggle(selectedRow) {    
    rowID = $$$(selectedRow).up('.nsDataRow').identify();
    rowWrap = $$$(rowID).down('div.nsRowWrap');
    vidID = rowID.replace(/detail-item-/, "cvp_ns_");
    classnamer = $$$(rowID).classNames().toString();
    classindex = classnamer.indexOf('expRow');
        
    if (classindex < 0) {
       rowReset();  
       expand(rowID, rowWrap);
       var addIn =  function(){           
           new Effect.Opacity(rowWrap, { 
              duration: 0.2,
              transition: Effect.Transitions.sinoidal,
              //queue: 'end'
              from: 0,
              to: 1
           });           
          
          $$$(rowID).addClassName('expRow');
          $$$(rowID).down('div.nsBlurb').setStyle({display: 'block'});
          $$$(rowID).down('span.nsToggler').innerHTML = "<img class='hidearrow' src='http://ddl-turkey.net/templates/ddl/images/content/hide.details.arrow.gif' />hide details";
          $$$(rowID).down('span.nsVideo').setStyle({display: 'inline'});
      }
      window.setTimeout(addIn, 310);  
    } else {
    	collapse(rowID, rowWrap);
        var cleanUp = function() {
            new Effect.Opacity(rowWrap, { 
               duration: 0.2,
               transition: Effect.Transitions.sinoidal,
               queue: 'end',
               from: 0,
               to: 1
            });
            
            $$$(rowID).removeClassName('expRow');
            $$$(rowID).down('div.nsBlurb').setStyle({display: 'none'});
            $$$(rowID).down('span.nsToggler').innerHTML = "<img class='hidearrow' src='http://ddl-turkey.net/templates/ddl/images/content/show.details.arrow.gif' />show details";
        }        
        window.setTimeout(cleanUp, 310); 
    }
}


function expand(rowID, rowWrap) {
    FB.XFBML.parse($$$('fb-' + rowID));
    $$$(rowID).down('div').setStyle({fontWeight: 'normal'});
    new Effect.Scale(rowID, 316.67, {
            transition: Effect.Transitions.sinoidal, 
            scaleX: false,
            scaleContent: false,
            scaleFromCenter: true,
            duration: 0.3, 
            queue: {position: 'front',  scope: 'expandRow'},
            scaleMode: {originalHeight: 60}
    });       
    

   new Effect.Opacity(rowWrap, { 
            duration: 0.3,
            transition: Effect.Transitions.sinoidal,
            //queue: {position: 'end',  scope: 'expandRow'},
            from: 1,
            to: 0
    });      
   $$$(rowID).down('div').setStyle({fontWeight : 'bold'});
    	
}

function collapse(rowId, rowWrap) {
    new Effect.Scale(rowID, 31.5, {
            transition: Effect.Transitions.sinoidal, 
            scaleX: false,
            scaleContent: false,
            scaleFromCenter: true,
            duration: 0.3, 
           // queue: {position: 'front',  scope: 'collapseRow'},
            scaleMode: {originalHeight: 190}
    });
    
    new Effect.Opacity(rowWrap, { 
            duration: 0.3,
            transition: Effect.Transitions.sinoidal,
            //queue: {position: 'end',  scope: 'collapseRow'},
            from: 1,
            to: 0
    });       
     
     $$$(rowID).down('span.nsVideo').setStyle({display: 'none'});        
     	
}

// to send debug log messages to
function console_log(string) {
//   console.log(string);
}

// CHECKBOX TOGGLER ////////////////////////////////////////////////////////
function topicToggle(selectedTopic, preFilter) {
      topic = $$$(selectedTopic).identify();
      var on = "http://ddl-turkey.net/templates/ddl/images/content/checkBox_on.gif";
      var off = "http://ddl-turkey.net/templates/ddl/images/content/checkBox_off.gif";       
      var is_All = $$$(selectedTopic).up('li').hasClassName('showMeAll');
      var is_Topic = $$$(selectedTopic).descendantOf('nsTopicList');
      var all_btn;
      var qArray;

      var equiv = function() {
         input_name = "ns" + topic.toString();
         
         if(input_name == "nstypeLink"){
             input_name = "nstype-all";
         } else if (input_name == "nstopicLink"){
             input_name = "nstopic-all";
         }         
         return input_name;
      }       
      var is_On = $$$F(equiv()).toString();
      
      console_log(topic);
      console_log(equiv());
      console_log(is_On);
      
      console_log("num 1: " + first_fire_top);
      
      //serialize data
      function serialIt() { 
         qArray = $$$('nsTopicControl').getInputs('hidden');
         console_log(qArray);
      }
      
      //turn the form values to on or off
      function rowOn() {   // turn the value on in the form field       
          formTopic = 'ns' + topic.toString();
          var value = $$$F(formTopic);
         $$$(formTopic).writeAttribute('value', 'on'); 
         serialIt();
         console_log(formTopic);
      }
      
      function rowOff() {   // turn the value on in the form field       
          formTopic = 'ns' + topic.toString();
          var value = $$$F(formTopic);
         $$$(formTopic).writeAttribute('value', 'off'); 
         serialIt(); 
         console_log('rowOff');
      }      
      
      function allOn(listing) {
          if(listing == "topic-all"){
              $$('.topFilter').each(function(s){
                      s.writeAttribute('value', 'on'); 
              });
              console_log('all on is running');
              first_fire_top = 0;
              serialIt();
         }
         else if(listing == "type-all") {
             $$('.typeFilter').each(function(s){
                      s.writeAttribute('value', 'on');                  
              });
             first_fire_type = 0;
             serialIt();
         }
         console_log('allOn');
         console_log(listing);
      }
      
      function allOff(listing) {
             console_log('allOff');
             
             if ((first_fire_type == 0) && (is_Topic == false)){
                 $$('.typeFilter').each(function(s){
                      s.writeAttribute('value', 'off');                  
                 });
                 first_fire_type = 1;
//                 serialIt();
                 console_log(first_fire_type);
             }             
             else if ((first_fire_top ==  0) && (is_Topic == true)){
                 $$('.topFilter').each(function(s){
                      s.writeAttribute('value', 'off');                  
                 });
                 first_fire_top = 1;
//                 serialIt();
                 console_log(first_fire_top);
             }  
             else {
                 rowOff();
             }
      }      
       //end turning form values on and off
      
      //turn checkboxes on and off
      if((is_All == true) && (is_On == 'on')) { // unselect all if already on
          
          console_log('they are all on');
          var sibs = $$$(selectedTopic).up().nextSiblings();  
          var which_all = $$$(selectedTopic).up('li').identify();
          console_log(all_btn + " " + sibs);
          
         // $$$(selectedTopic).removeClassName('topicON');
          //$$$(selectedTopic).down().writeAttribute('src', off);
          
          $$$(sibs).each(function(s) { 
            console_log(s.down('a'));
            //s.down('a').removeClassName('topicON');
            //s.down('img').writeAttribute('src', off);           
          });   
          //allOff(which_all);
      }          
      else if(is_All == true){ // select all if all aren't on                    
          var sibs = $$$(selectedTopic).up().nextSiblings(); 
          var which_all = $$$(selectedTopic).up('li').identify();
          $$$(selectedTopic).addClassName('topicON');
          $$$(selectedTopic).down().writeAttribute('src', on);
          
          $$$(sibs).each(function(s) { 
             s.down('a').removeClassName('topicON');
             //s.down('a').addClassName('topicON');
             //$$$(selectedTopic).down().writeAttribute('src', on);
             s.down('img').writeAttribute('src', off);
             console_log(s.down('img').identify());
          });
          allOn(which_all);
      }
      else if (is_On == 'off') { // turn 1 on          
         $$$(selectedTopic).down().writeAttribute('src', on);
         $$$(selectedTopic).addClassName('topicON');
         //if All is selected
         $$$(selectedTopic).up('ul').firstDescendant('showMeAll').down('img').writeAttribute('src', off);
         $$$(selectedTopic).up('ul').firstDescendant('showMeAll').down('a').removeClassName('topicON');
                    
          if ((is_Topic ==  false)&&(first_fire_type == 0)) {
              allOff(topic);
              rowOn();
              console_log(first_fire_top);
          }
          else if ((is_Topic= true)&&(first_fire_top == 0)){
              allOff(topic);
              rowOn();
          }          
          else{
              rowOn();
          }
          
          
      } else if (is_On == 'on'){ // turn 1 off          
          $$$(selectedTopic).down().writeAttribute('src', off);
          $$$(selectedTopic).removeClassName('topicON');
          //If "ALL" is selected          
          $$$(selectedTopic).up('ul').firstDescendant('showMeAll').down('img').writeAttribute('src', off);
          $$$(selectedTopic).up('ul').firstDescendant('showMeAll').down('a').removeClassName('topicON');
          
          console_log("num 2: " + first_fire_top);
          
          if ((is_Topic ==  false)&&(first_fire_type == 0)) { 
              allOff(topic);
              rowOn();
              $$$(selectedTopic).addClassName('topicON');
              $$$(selectedTopic).down().writeAttribute('src', on);
          } else if ((is_Topic ==  true)&&(first_fire_top == 0)) {
              allOff(topic);
              rowOn();
              $$$(selectedTopic).addClassName('topicON');
              $$$(selectedTopic).down().writeAttribute('src', on);
              
          }
          else {
              rowOff();
          }         
      }    
      // end turn checkboxes on and off
      
      console_log("num 2: " + first_fire_top);
      var fString = "";
      if (qArray[0].value == "on") {
        fString = "";
      } else {
          var x = 1;
          while(!(!( qArray[x]||false )) && x < 13) {
              if (qArray[x].value == "on") {
                  fString = fString + qArray[x].name + ",";
              }
              x += 1;
          }
      }

      if ((fString == "") && (qArray[0].value == "off")) {
          allOn('topic-all');
          $$$('topicLink').down().writeAttribute('src', on);
          $$$('topicLink').addClassName('topicON');
      }

        var tString = "";
      
      	if (qArray[13].value == "on") {
              tString = "";
		} else {
		    var x = 13;
		    while(!(!( qArray[x]||false ))) {
		        if (qArray[x].value == "on") {
		        	tString = tString + qArray[x].name + ",";
		        }
		        x += 1;
		    }
		}
    if ((tString == "") && (qArray[13].value == "off")) {
        allOn('type-all');
        $$$('typeLink').down().writeAttribute('src', on);
        $$$('typeLink').addClassName('topicON');
    }

      $$$('filters').value = fString + tString;
      $$$('start').value = 0;
      if (!preFilter) {
        updateContent('listing-container', '/filter', Form.serialize('valueForm'));
//        $$$('nsSearchBox').value = 'Filter by keyword';
      }
      
      
      console_log('fString - ' + fString + tString);
      return;
}

function updateContent(container, url, params) {
    if (hasKeywords()) {
        url = '/search';
    }
    url = $$$F('ROOT') + url;
    rePingOmniture();
    new Ajax.Updater(container, url, { method: "get", parameters: params, evalScripts: true });
}

function addContent(container, url, params) {
    if (hasKeywords()) {
        url = '/search';
    }
    url = $$$F('ROOT') + url;
    rePingOmniture();
    new Ajax.Updater(container, url, { method: "get", parameters: params, evalScripts: true, insertion: Insertion.Bottom});
}

function hasKeywords() {
    return false;

    var k = $$$F('keywords');
    if (k == "") {
        return false;
    }
    return true;

}

function changeRange(select) {
    var range = select.options[select.selectedIndex].value;
    var r = $$$F('range');
    if (r != range) {
        $$$('range').value = range;
        $$$('start').value = 0;
        updateContent('listing-container', '/filter', Form.serialize('valueForm'));
//        $$$('nsSearchBox').value = 'Filter by keyword';
    }
    return false;
}

function showMore() {
    var start = parseInt($$$F('start'));
    start += 1;
    $$$('start').value = start;
    addContent('listing-container', '/filter', Form.serialize('valueForm'));
    return false;
}

function updateLoadMoreLabel(current, total) {
    if ($$$('nsRange')) {
        $$$('nsRange').update(current);
        $$$('nsTotal').update(total);
        $$$('nsShowResultLoad').update(current);
        $$$('nsShowResultTotal').update(total);
        if (current == total) {
            $$$('nsLoadMoreWrapper').setStyle({display: 'none'});
        } else {
            if ($$$('nsLoadMoreWrapper').getStyle('display') == 'none') {
                $$$('nsLoadMoreWrapper').setStyle({display: 'inline'});
            }
        }
    }
}

function rePingOmniture() {
    var o = "RANGE:";
    o += $$$('range').value;
    o += ",START:";
    o += $$$('start').value;
    var f = $$$('filters').value;
    if (f) {
        o += ",FILTERS:";
        o += f;
    }
    newsPulseOmniCall(o);
}

function processPreFiltered(topic, range) {
    var select = $$$('nsTimeDrop');
    select[select.selectedIndex].selected = 0;
    for (var x = 0; x < select.options.length; x++) {
        if (select[x].value == range) {
            select[x].selected = 1;
        }
    }
    jQuery('#nsTimeDrop').resetSS();
    $$$('range').value = range;
    var t = $$$('topic-' + topic);
    topicToggle(t, true);
}

///ODD - EVEN ////////////////////////
/*
Event.observe(window, 'load', function() {
    $$('.nsData > li.nsDataRow:nth-child(even)').each(function(s) {
            s.setStyle({backgroundColor: '#f3f3f3'});
    });
});
*/


