//var basePath = 'http://127.0.0.1/theora'	
var basePath = 'http://theoradesign.com';

var currentPage = 0;
var isStart = true;
var slide = null;
var panelCnt = 0;
var extraQ = false;
var mySlideShow = null;

// var idsPerPage = [];

var cardArray = [];
var menuAction = null;
var menuopen = false;

var closeM = function closeMenu(e) {
   var event = new Event(e);
   event.stop();  
   if(event.page.y > 140 && menuopen) {       
   //  console.log('---- Out -----');
      
      $('sub_menu').removeEvent();
      menuopen = false;
    // $('main_menu').setStyle('height', 52);
     // menuAction.toggle()
     (function(){menuAction.toggle()}).delay(30);    
   } 
}

var showM = function showMenu(e) {  
   var event = new Event(e);  
   event.stop();
   if(event.page.y < 62 && !menuopen) {
      menuopen = true;
      menuAction.toggle().chain(function(){
         $('sub_menu').addEvent('mouseout', closeM);
      }); 
      $('main_menu').setStyle('border-bottom', 'none'); 
   }                 
}

                   
function initGame() { 
   cardArray = [];
   isStart = true;
   var submenu = $('sub_menu');
   menuAction = new Fx.Slide(submenu,  {duration: 500});
   menuAction.hide();
   submenu.setStyle('display', 'block');
   
   var menuElement = $('main_menu');
   menuElement.addEvent('mouseover', showM);
   
   slide = new Fx.Scroll('cardsContainer', {duration: 700});
   
  
   if(typeof sIFR == "function"){

	  sIFR.replaceElement(named({sSelector:"ul#top_nav li h5", sFlashSrc: basePath + "/assets/flash/animeace2_bld.swf", 
                                 sColor:"#13B8DF", sBgColor:"#FCFEEF",  sWmode:"transparent", sFlashVars:"textalign=left&width=130&height=28&offsetLeft=5"}));
      sIFR.replaceElement(named({sSelector:"h2.sifr_big", sFlashSrc:basePath +  "/assets/flash/TT0728M.swf", 
                                 sColor:"#faa00e", sBgColor:"#FCFEEF",  sFlashVars:"height=32"}));
      sIFR.replaceElement(named({sSelector:"span.sifr_main", sFlashSrc:basePath +  "/assets/flash/TT0728M.swf", 
                                 sColor:"#faa00e", sBgColor:"#FCFEEF",  sFlashVars:"height=20&width=70"}));                           
      sIFR.replaceElement(named({sSelector:"h5.sifr_med", sFlashSrc:basePath +  "/assets/flash/TT0728M.swf", 
                                 sColor:"#754C24", sBgColor:"#FCFEEF",  sFlashVars:"height=32"}));                                                          
      sIFR.replaceElement(named({sSelector:"h5.sifr_blue", sFlashSrc:basePath +  "/assets/flash/TT0728M.swf", 
                                       sColor:"#196771", sBgColor:"#FCFEEF",  sFlashVars:"height=14"}));          
   }



   var so = new SWFObject( basePath + '/assets/flash/theoranimation.swf', "theora-anim", "110", "916", "8", "#fcfeef");
   so.write("hold_left");

   for(var j = 0;  j < 9; j++) {
      doFlashCard(j, 'x', '', '');
   }
   
   addFrameToImg();
   
    if ((window.ie6) && (document.body.filters)) { 
        /*supersleight.limitTo('search_fly');*/
        supersleight.run();
    }
}

function doFlashCard(idx, title, img, link) {
    var so;
    /*if(title == '' && img == '')
      return;
     */ 
    var children = $('gameCards').getChildren();
    var item = children[idx];
    
    if( idx >= children.length) {
       return;
    }
    if(link == 'empty') {
       item.setHTML('<img src="/assets/templates/theora/images/gw_unit.png" />');
       return;
    }
    so = new SWFObject( basePath + '/assets/flash/gw_unit.swf', "gameCard_" + idx, "100", "130", "8", "#E4F5ED");
    if(title == 'x') {
       var el = item.getFirst();
       so.addVariable("ttl", el.getFirst().getProperty('alt'));
       so.addVariable("img", el.getFirst().getProperty('src'));
       so.addVariable("uri", el.getProperty('href'));    
    }
    
    else {
       so.addVariable("ttl", title);
       so.addVariable("img", img);
       so.addVariable("uri",  link );
    }
    so.addVariable("wmode", "transparent");
    so.addParam("wmode", "transparent");
    so.write(item);
}

function showResults(num) {
   var res = $$("div#results");
   res.setStyle('display', 'inline');
	res.getFirst().setText(num);
}


// generates the first card panel per search question
function generateFirstpage(cards, sql) {

   var links = '';
   var link;
   var ref;
   var imgSrc;
   
    var thumbs = '';
    var t;
    for(t = 0; t < 9; t++) {      
       thumbs += '<div class="thumb"></div> ';
    }
    var cardsContainer = $('gameCards'); 
    cardsContainer.setHTML(thumbs);
    
	 
	 // place the flash elements
	 for(var j = 0;  j < 9; j++) {
	   if(j < cards.length ) {
	     imgSrc = '/assets/images/S2/' + cards[j].pic;
	     ref = '/product?id=' + cards[j].id ;
        // "javascript:ajaxShowGallery(" + cards[j].box +  ',' + cards[j].serial + ')';
	     doFlashCard(j, cards[j].title,imgSrc, ref); 
	   }
	   else {
	      doFlashCard(j, '', '', 'empty'); 
	   }
	 }
	 
	 
    // hide 'back' button
    $('lPage').setStyle('display', 'none');
    // show 'next' button if appropriate
    $('rPage').setStyle('display', (cards.length > 9) ? 'inline' : 'none' );
	 showResults(cards.length);
}



var ajaxGetCompOptions = function() {
   var toReplace = $$('li#pubBy')[0];
   if((!$defined(toReplace)) || toReplace.getFirst().length > 2)
      return;
   var sel = $('company_full').clone();
   sel.setStyle('display', 'inline');
   
   toReplace.replaceWith(sel);
}



var qPanelOpen = false;
function expandQuestions() {
   var el = $('search_fly');
   if(!qPanelOpen) {
      el.setStyle('display', 'block');      
       
       new Fx.Styles(el, {duration: 400})/*.addEvent(
                                       'onComplete', ajaxGetCompOptions)*/.start(
                     {
                      'bottom': [-200, 2] 
                     });            
      qPanelOpen = true;
   }
   else {
      new Fx.Styles(el, {duration: 600}).start(
                                       {'bottom': [2, -200]}).addEvent(
                                       'onComplete', function(item) {
                                          item.setStyle('display', 'none');                           
                                       });
                                         
      qPanelOpen = false;
   }                                  

}
   
var gameReq = function gameRequest() {
        
   var jsonParams = [];
   var idx = 0;
   
   // build the query params from the drop down boxes
   $$('select.question').each(function(item, index) {
      var li = item.getParent();
      if((item.selectedIndex >= 0) && (li.getStyle('display') != 'none')) {
         var n = item.name;
         jsonParams[idx] = {'question' : item.name,
                            'param' : item.options[item.selectedIndex].value};
         idx++;
      }
   })
   url = basePath + '/assets/snippets/theora/filterCards.php'
   
   /*+++
   $('innerSlideBox').empty();  
   $('innerSlideBox').setStyle('width', 301); 
    */

   var el = $('gameCards'); 
   el.empty();  
   el.setStyle('width', 301);
   showResults('?');
   
	new Json.Remote(url, {
		  onComplete: function(jsonObj) {		    
            var cards = jsonObj.dat; 	
   			isStart = false;			  			
            cardArray = cards.copy();		   
            generateFirstpage(cards, '');
   		   currentPage = 0;
		}	   
	}).send(jsonParams);

}

/*
*/

function directSearch() {
    var txt = $('directSrch').getElement('input').value;
    window.location = '/projects?val=' + txt;
}
    
    
function directSearch_old() {
    var txt = $('directSrch').getElement('input').value;
    url = basePath + '/assets/snippets/theora/searchItem.php';
    jsonParams = [];
    jsonParams[0] = {'question' : 'direct',
                     'param' : txt};
    /*  
	new Json.Remote(url, {
		  onComplete: function(jsonObj) {		    
            var cards = jsonObj; 	
            isStart = false;	
            if((cards != null) && (cards.length > 0)) {
               
               var ids = '';
               var i = 0;
               while(i < cards.length) {
                  ids += cards[i].id;
                  if(i != cards.length-1) 
                     ids += ',';
                  i++;
               }
               window.location = '/projects?ids=' + ids ;
      		   currentPage = 0;
      		}
		}	   
	}).send(jsonParams);*/
}



/* this function is called in response to selecting an option from 
   the before/in/after dropdown.
   it performs a query only if the year is selected already
*/
function askTimeDesc(el, isTop) {
   el = $(el);
   var yearQ = el.getNext();
   if(yearQ.options[yearQ.selectedIndex].value != '-1') {
       askAnother(el, isTop);
   }
}

function getOrd(li) {
   var ord = 0;
   var tempLi = li.getParent().getFirst();
   while(tempLi != li) {
      ord++;
      tempLi = tempLi.getNext();
   }
   return(ord);
}


/**
 * handles the closing of the extra question panel, and moving the question 
 * to the permanent question panel. Then it calls gameReq().
 */   
function askAnother(el, isTop) {
   el = $(el);
   var li = el.getParent();
   if(!isTop) {
      gameReq();
   }
   else {
      new Fx.Style(li, 'opacity', {duration: 800}).start(0.1)
         .chain(function() {                                                    
            li.setStyle('display', 'none');
            // close panel
            expandQuestions();   
            /*
            li.getFirst().getFirst().setProperty('selected','selected'); 
            */
            var ord = getOrd(li);
            var bottomUl = $('srch_ul');
            var bottomLi = bottomUl.getChildren()[ord];
            var liArray = li.getChildren();
            for(j = 0; j < liArray.length; j++) {
               bottomLi.getChildren()[j].selectedIndex = liArray[j].selectedIndex;
            }
            bottomLi.setStyle('display', 'block');             
         }).chain(gameReq());
      }                                                     
}

function moveUp(el) {
   el = $(el);
   var li = el.getParent();
   li.setStyle('display', 'none');
   var ord = getOrd(li);
   var topUl = $$('div#search_fly ul')[0];
   var upperLi = topUl.getChildren()[ord];
   upperLi.setOpacity(1);
   upperLi.setStyle('display', 'block');
   for(j = 0; j < upperLi.getChildren().length; j++) {
      upperLi.getChildren()[j].selectedIndex = 0;
   }
}     
     
     

function moveToPage() {
   var newPanel = false;
   var newDiv;

// do effect
      
   var from = currentPage * 9;

    // replace the flash elements
	 for(var j = from; j < from + 9 ; j++) {
	   if(j < cardArray.length ) {
	     imgSrc = '/assets/images/S2/' + cardArray[j].pic;
	     ref = '/product?id=' + cardArray[j].id;
        //ref = "javascript:ajaxShowGallery(" + cardArray[j].box +  ',' + cardArray[j].serial + ')';
	     doFlashCard(j%9, cardArray[j].title,imgSrc, ref); 
	   }
	   else {
	      doFlashCard(j%9, '', '', 'empty'); 
	   }
	 }
    
   /*$("debug").setText((currentPage+1) + ' | '  + ((Math.floor((cardArray.length-1) / 9)) + 1) );*/
}


function moveLeftPage() {
   if(currentPage > 0) {
      currentPage--;   
      moveToPage();
      if(currentPage == 0) {
         $('lPage').setStyle('display', 'none');
      }
      if(currentPage == Math.floor((cardArray.length-1) / 9) - 1) {
         $('rPage').setStyle('display', 'inline');
      }
   }
}


function moveRightPage() {
   var lastPage = Math.floor((cardArray.length-1) / 9);
   if(lastPage > currentPage) {
      if(currentPage == 0) {
         $('lPage').setStyle('display', 'inline');
      }
      if(currentPage == lastPage - 1) {
         $('rPage').setStyle('display', 'none');
      }
      currentPage++;
      moveToPage(); 
      
   } 
}


function startGallery() {
   if(mySlideShow != null)
   {
      mySlideShow.stopShow();
   }
   
   mySlideShow = new mooSimpleSlide(
      {period:11000,
       imageSelector: 'img.gallery_img'
      });
   if ((window.ie6) && (document.body.filters)) {   
      supersleight.limitTo('s_gallery');
      supersleight.run();
   }      	
}


function ajaxShowGallery(id) {
   var params = 'id=' + id;  
   new AjaxLink('hold_center', params, startGallery, null);
}



/*
  onLoadFunc: array containing a function to be executed when the ajax call 
               is completed

  funcParams: single value or array containing parameters to the function
   
*/     
/*
new AjaxLink('content',['b=94','s=4'], startGallery, null)
*/
          
var AjaxLink = new Class({
	initialize: function(container, phpParams, onLoadFunc, funcParams){
		
      new Fx.Style(container, 'opacity', {duration: 600}).start(0.35);
      container = $(container);		
   	
   	/*alert(phpParams);*/
		
      var ajax = new Ajax(basePath + '/product-ajax',{
				method: 'get',
				update:container,
				onSuccess:function(res){
				   
					new Fx.Style(container, 'opacity', {duration: 500}).start(1);
            	if(onLoadFunc != null) {
            	   if(funcParams != null)
                     onLoadFunc.pass(funcParams)();
                  else
                    onLoadFunc.attempt([])   
                  
                  sIFR.replaceElement(named({sSelector:"h5.sifr_blue", sFlashSrc:basePath +  "/assets/flash/TT0728M.swf", 
                                       sColor:"#196771", sBgColor:"#FCFEEF",  sFlashVars:"height=14"}));                          
               }   
				}
		});
		ajax.request(phpParams);

	
	}
})


/*  onload="addFrameToBlogImg()"*/

function addFrameToImg() {
    $$('img.decImg').each(function(item, index) {
          
          var imdiv = new Element('p', {'class': 'blogImg'});
          new Element('img', {
                              'src': basePath + '/assets/templates/theora/styles/img/blog_image-frame.png',
                              'class': 'blogImgFrame'
                           }).injectInside(imdiv);
          var cloned = item.clone();   
          cloned.setProperty('height', 225);
          cloned.setProperty('width', 340);              
          cloned.injectInside(imdiv);       
          item.replaceWith(imdiv);
          cloned.setStyle('display', 'inline');
          var cap = new Element('span', {
                       'class': 'blog_img_caption'}).injectInside(imdiv); 
          cap.setText('     ' + item.getProperty('alt')); 
                       
   })
   
 //  if ((window.ie6) && (document.body.filters)) { 
  //      supersleight.limitTo('hold_center');
  //      supersleight.run();
  //  }
}
                 
/*
function addFrameToImg() {
    $$('img.decImg').each(function(item, index) {
      
       var imgUrl = 'url(' + item.getProperty('src') + ') no-repeat';  
       var imdiv = item.getParent();//new Element('p', {'class': 'blogImg'});
       imdiv.set({'class': 'blogImg',
                  'styles': 
                     {'background': imgUrl}
                });   
                  
       new Element('img', {
                           'src': basePath + '/assets/templates/theora/styles/img/img_frame.png',
                           'class': 'blogImgFrame'
                        }).injectInside(imdiv);
       
       var cap = new Element('span', {
                    'class': 'blog_img_caption'}).injectAfter(imdiv); 
       cap.setText('     ' + item.getProperty('alt')); 
       item.remove();
                       
   })
   
}*/
var discState=false;                 
function openDisc() {
    if(discState == false) {
       discState = true;
       $$('div#disclaimer p')[0].setStyle('display', 'block');
    }
    else {
       discState = false;
       $$('div#disclaimer p')[0].setStyle('display', 'none');
    }                       
}
                                  
                        
window.addEvent('domready', initGame);
