pimpedPCRatings = new Array();
myRating = 0;
pimpedPCId = 0;
pimpUsername = '';
numPCs = 0;

var pimpmypcEngine = {
  init: function(page) {
    pimpmypcEngine.output_comments();
    var commentsRefresher = new PeriodicalExecuter(pimpmypcEngine.refresh_comments, 300);
    pimpmypcEngine.renderDice();
    pimpmypcEngine.renderModBar();
	},
	
	refresh_comments: function() {
  	var myAjax = new Ajax.Request('/include/forumFeed_js.php', {
  		method: 'get',
  	  requestHeaders: ['Cache-Control', 'no-cache, must-revalidate, no-store', 'Expires', '0', 'pragma', 'no-cache'],
  	  parameters: 'pimpedPCId=' + pimpedPCId,
  		onSuccess: function(req){
  				  eval(req.responseText);
          	pimpmypcEngine.output_comments();
            }   		  
    });
  },
	
	output_comments: function() {
	  forumEngine.output_comments('pimpedPCComments');
  },	

  showImg: function(img) {
      var newMainImageSrc = $('image' + img).src.substr(0, $('image' + img).src.indexOf('&w')) + '&w=450';
      $('image' + img).src = $('mainImage').src.substr(0, $('mainImage').src.indexOf('&w')) + '&w=60&h=60';
      $('mainImage').src = newMainImageSrc;
      var newMainImageCaption = $('caption' + img).value;
      $('caption' + img).value = $('mainImageCaption').innerHTML;
      $('mainImageCaption').innerHTML = newMainImageCaption;
  },
  
	rateIt: function(rating) {
	  if (my.id < 1) {
      loginMsg = "Du m&aring; v&aelig;re p&aring;logget som bruker av ITavisen.no for &aring; gi terningkast eller legge inn din egen maskin p&aring; Pimp My PC.";
      doAfterLogin = "pimpmypcEngine.rateIt(rating);";
      fpEngine.showLoginScreen(loginMsg);
    } else {
    	document.body.style.cursor = "wait";
      $('die_' + rating).style.cursor = "wait";
      var myAjax = new Ajax.Request('/pimpmypc/pimpmypc_action.php', {
    		method: 'post',
    	  requestHeaders: ['Cache-Control', 'no-cache, must-revalidate, no-store', 'Expires', '0', 'pragma', 'no-cache'],
    	  parameters: 'task=ratePC&pimpedPCId=' + pimpedPCId + '&rating=' + rating + '&ajax=' + new Date() * 1,
    		onSuccess: function(req){
          if (req.responseText && req.responseText.match(/avgRatingDie/i)) {
            $('ratingSummary').innerHTML = req.responseText;
            myRating = rating;
            pimpmypcEngine.renderDice();          		 
          } else  {
            alert(req.responseText);
          } 
          document.body.style.cursor = "default";
          $('die_' + rating).style.cursor = "pointer";
        }   		  
      });
    }
  },
  
  renderDice: function() {
    if (myRating == 0){ myRating = pimpmypcEngine.get_myRating(); }
    
    $$('.die').each(function(el){    	
      currentDie = el.id.replace('die_', '');
      if ((currentDie != myRating) && (my.id > 0) && (myRating > 0)) Element.addClassName(el, "highlight");
      else if (Element.hasClassName(el, "highlight")) Element.removeClassName(el, "highlight"); 
    })
  },
  
  get_myRating: function(){
    myRating = 0;
    /*pimpedPCRatings.each(function(rating){
      // rating[0] = 'readerUsername', rating[1] = rating
      if (rating[0] == my.username) myRating = rating[1];
    })*/
    
    var myAjax = new Ajax.Request('/pimpmypc/pimpmypc_action.php', {
		method: 'post',
		requestHeaders: ['Cache-Control', 'no-cache, must-revalidate, no-store', 'Expires', '0', 'pragma', 'no-cache'],
		parameters: 'task=getMyRating&pimpedPCId=' + pimpedPCId + '&ajax=' + new Date() * 1,
		onSuccess: function(req){			
			if(req.responseText>0){				
				myRating = req.responseText;
				
				$$('.die').each(function(el){    	
			      currentDie = el.id.replace('die_', '');
			      if ((currentDie != myRating) && (my.id > 0) && (myRating > 0)) Element.addClassName(el, "highlight");
			      else if (Element.hasClassName(el, "highlight")) Element.removeClassName(el, "highlight"); 
			    })
			}
		}   		  
	});
	
    return myRating;
  },
  
  doLogIn: function() {
	  pimpmypcEngine.renderDice();
    pimpmypcEngine.renderModBar();
  },
	
	doLogOff: function() {
	  pimpmypcEngine.renderDice();
    pimpmypcEngine.renderModBar();
  },
  
  registerComment: function() {
    if (($F('commentInputText') === 'Skriv her...') || !$F('commentInputText')) {
      alert("Du m&aring; skrive noe i kommentarfeltet f&oslash;rst!");
      $('commentInputText').clear();
      $('commentInputText').focus();
    }
    else if (my.id < 1) {
      loginMsg = "Du m&aring; v&aelig;re p&aring;logget som bruker av ITavisen.no for &aring; skrive kommentarer.";
      doAfterLogin = "forumEngine.submitPost($F('commentInputText'), 'pimpedPC');";
      fpEngine.showLoginScreen(loginMsg);
    } else {
      forumEngine.submitPost($F('commentInputText'), 'pimpedPC');
    }
  },
  
  renderModBar: function() {
    if ($('modBarArea')) {
      if (ur_mod() || (my.username == pimpUsername)) {
        output = '<div id="modBar"><div style="padding: 4px 4px 4px 8px;">';
        output += '<a href="javascript: pimpmypcEngine.editPC();">rediger maskin</a> &nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; ';
        output += '<a href="javascript: pimpmypcEngine.deletePC();">slett maskin</a>';
        output += '</div></div>';
        $('modBarArea').innerHTML = output;
      } else {
        $('modBarArea').innerHTML = '';
      }
    }
  },
  
  deletePC: function() {
    if ((pimpUsername == my.username) || ur_mod()) {
      if (confirm("Virkelig slette denne maskinen?")) {
        if (pimpUsername != my.username) {
          promptMsg = 'Brukeren vil f&aring; beskjed p&aring; mail om at du har slettet PCen. \n\nHvilken grunn skal vi oppgi?\n\nHer er noen snarveier til standard&aring;rsaker(bare skriv inn tallet):\n\n';
          reason1 = 'Duplikat: PCen finnes fra f&oslash;r.';
          reason2 = 'Mangelfull eller ingen beskrivelse.';
          reason3 = 'Uakseptabelt bilde';
          reason4 = 'Mulig vi tar feil, men dette ser ikke ut til &aring; v&aelig;re din egen maskin.';
          reason5 = 'Dette ser ut til &aring; bare v&aelig;re er middels standard-PC med bilde rett fra produsentens hjemmeside. ';
          promptMsg += '1 - ' + reason1 + '\n';
          promptMsg += '2 - ' + reason2 + '\n';
          promptMsg += '3 - ' + reason3 + '\n';
          promptMsg += '4 - ' + reason4 + '\n';
          promptMsg += '5 - ' + reason5 + '\n';
          var reason = prompt(promptMsg, '');
          for (i = 1; i <= 5; i++) {
            if (reason == i) reason = eval('reason' + i);
          }
          if (!reason) return;
        } else {
          var reason = '';
        }
      var myAjax = new Ajax.Request('/pimpmypc/pimpmypc_action.php', {
      		method: 'post',
      	  requestHeaders: ['Cache-Control', 'no-cache, must-revalidate, no-store', 'Expires', '0', 'pragma', 'no-cache'],
      	  parameters: 'task=deletePC&pimpedPCId=' + pimpedPCId + '&reason=' + encodeURIComponent(reason) + '&ajax=' + new Date() * 1,
      		onSuccess: function(req){        
            if (req.responseText) alert(req.responseText);
            else pimpmypcEngine.getRandomPC();
            // else top.location.href = "/pimpmypc/";
          }   		  
        });
     }
    }
  },
  
  editPC: function() {
    if (ur_mod() || (pimpUsername === my.username)) top.location.href = '/pimpmypc/rediger/' + pimpedPCId;
  },
  
  submitPimpSearch: function() {
    searchQuery = $F('searchQuery');
    skip = $F('skip');
      top.location.href = '/pimpmypc/finn/' + encodeURIComponent(searchQuery);
  },
  
  goToEnterPCForm: function() {
    if (my.id < 1) {
      loginMsg = "Du m&aring; v&aelig;re p&aring;logget som bruker av ITavisen.no for &aring; bruke Pimp My PC.";
      doAfterLogin = "pimpmypcEngine.goToEnterPCForm();";
      fpEngine.showLoginScreen(loginMsg);
      return;
    }
    top.location.href = "/pimpmypc/ny/"; 
  },
  
  getRandomPC: function() {
    top.location.href = "/pimpmypc/tilfeldig/" + Math.round(numPCs * Math.random());
  },
  
  reportPimpedPC: function(pimpedPCId) {
      if (!pimpedPCId) return;
      reason = prompt('Hvis du mener det er noe galt med dette PimpMyPC-innlegget, og du &oslash;nsker at moderatorene skal ta en n&aelig;rmere titt p&aring; den (evt. fjerne den), vennligst oppgi begrunnelsen din for dette &oslash;nsket her: ', '');
      if (reason) {
        var myAjax = new Ajax.Request("/pimpmypc/pimpmypc_action.php", {
          method: 'post',
          requestHeaders: ['Cache-Control', 'no-cache, must-revalidate, no-store', 'Expires', '0', 'pragma', 'no-cache'],
          parameters: 'task=reportPC&pimpedPCId=' + pimpedPCId + '&reason=' + encodeURIComponent(reason) + '&ajax=' + new Date() * 1,
          onSuccess: function(req){
              if (req.responseText) {
                alert(req.responseText);
              } else {
                alert('Takk! Din kommentar er registrert, og ITavisens moderatorer vil bli varslet. ');
                $('pimpVarsling').style.display = 'none';
              }
            }
          });
      }
  }
  
}
