//Global variables for vote control management
var mvote_is_login=false;//Forum login flag
var mvote_user='';//User name if logged in
var mvote_collector_full_url=mvote_collector_url+check_sid();//Full collector URL including session ID
var mvote_captcha=mvote_collector_full_url+'?module=votecontrol&action=captcha&timestamp='+(new Date()).getTime();//Captcha source
var mvote_is_optin=false;//Opt-in flag
var mvote_objects=new Array();//Data model objects list
var mvote_controls=new Array();//Link list for controls and objects: control => object
var mvote_titles=new Array();//Vote control titles list
//Events listeners
var mvote_captcha_listener=null;//Captcha source on change listener
var mvote_before_login=null;//Called before login (returns boolean: false - cancel login, true - continue). Parameter: control id
var mvote_after_login=null;//Called after login (returns boolean: false - call logout, true - continue). Parameter: control id
var mvote_before_logout=null;//Called before logout (returns boolean: false - cancel logout, true - continue)
var mvote_after_logout=null;//Called after logout (returns boolean: false - error message, true - continue)
var mvote_before_register=null;//Called before register (returns boolean: false - cancel register, true - continue). Parameter: control id
var mvote_after_register=null;//Called after register (returns boolean: false - error message, true - continue). Parameter: control id

//Looking cookies for session id. Returns sid extension or empty string.
function check_sid() {
 var result='';
 cookie=document.cookie.split('; ');
 for (var i=0;i<cookie.length;i++) {
  crumb=cookie[i].split('=');
  if (crumb[0]=='marketocracy_sid') {
   result=';jsessionid='+crumb[1];
   break;
  }
 }
 return result;
}

//Makes request to AJAX handler at a server
function ajax_request(model,options,success_func) {
 var req=new JsHttpRequest();
 req.model=model;
 req.onsuccess=success_func;
 req.onreadystatechange=function() {
  if (req.readyState==4) {req.onsuccess(req);}
 }
 //Set login name to object in case of login or register request
 if (options.action==='login' || options.action==='register') {
  req.login_name=options.username;
 }
 //Prepare request object (automatically choose GET or POST)
 req.open(null,mvote_collector_full_url,true);
 //Send data to backend
 req.send(options);
}

//Show AJAX error
function ajax_error(msg) {
 alert(msg);
}

//Set appropriate variables when user logged out
function user_logout() {
 mvote_is_login=false;
 mvote_user='';
}

//Vote control data model object
//Constructor for the object
function vcontrol_data(forum,url) {
 //Sets properties
 this.forum=forum;
 this.url=url;
 this.avg_rate=0;
 this.avg_count=0;
 this.rate='';//Empty string = unrated
 this.tags='';
 this.active_control=0;//Active control (clicked) to interract with user via appropriate control
 this.active=false;
 this.inuse=false;
 this.loaded=false;
 this.is_init=false;//Initialization process flag (TRUE while first update of controls within loading routine)
 this.is_comment=false;//Data sending control parameter: TRUE - after login it sends comment, FALSE - after login it sends vote
 this.controls=new Array();
 //Methods
 this.addlink=vcontrol_data_addlink;
 this.update=vcontrol_data_update;
 this.update_all=vcontrol_data_update_all;
 this.load=vcontrol_data_load;
 this.vote=vcontrol_data_vote;
 this.comment=vcontrol_data_comment;
 this.send_vote=vcontrol_data_send_vote;
 this.send_comment=vcontrol_data_send_comment;
 this.login=vcontrol_data_login;
 this.logout=vcontrol_data_logout;
 this.register=vcontrol_data_register;
 this.use=vcontrol_data_use;
 this.release=vcontrol_data_release;
 this.refresh_captcha=vcontrol_data_refresh_captcha;
}

//Update control to model state
function vcontrol_data_update(control) {
 if (this.loaded) {
  //Update rating info
  var info=document.getElementById('mvote_info'+control);
  var count=this.avg_count;
  if (count==undefined || this.avg_rate==undefined) {count=0;}
  info.innerHTML='<strong>'+mvote_texts.infobar_title+'</strong>'+(count==0?mvote_texts.not_yet_rated:this.avg_rate+' ('+count+' '+(count==1?mvote_texts.vote:mvote_texts.votes)+')');
  var i;
  //Update images
  for (i=0;i<7;i++) {
   img=document.getElementById('mvote_img'+control+'_'+(i+1));
   img.src=mvote_images_path+(this.active && !this.inuse?mvote_images_inactive_off[i]:mvote_images_disabled_off[i]);
   img.style.cursor=this.active && !this.inuse?'pointer':'default';
  }
  //Update rate if already rated
  if (this.rate!=='') {
   num=new Number(this.rate);
   num+=4;
   document.getElementById('mvote_img'+control+'_'+num).src=mvote_images_path+(this.active && !this.inuse?mvote_images_inactive_on[num-1]:mvote_images_disabled_on[num-1]);
  }
  if (mvote_comment_on) {
   //Update tags field
   if (this.is_init) {document.getElementById('mvote_tags'+control).value=this.tags;}
   //Update send comment button state
   document.getElementById('mvote_comment_sendbtn'+control).disabled=this.inuse || !this.active;
  } 
  //Set visibility state
  document.getElementById('mvote_loader'+control).style.display='none';
  document.getElementById('mvote_bar'+control).style.display=mvote_styles.vote_bar;
  document.getElementById('mvote_login_info'+control).style.display=mvote_is_login?mvote_styles.login_info:'none';
  if (mvote_is_login) {document.getElementById('mvote_login_as'+control).innerHTML=mvote_user;}
  info.style.display=mvote_styles.info;
 }
}

//Update all controls to model state
function vcontrol_data_update_all() {
 var i;
 for (i in this.controls) {
  this.update(this.controls[i]);
 }
}

//Refresh captcha source for controls with opened registration form
function vcontrol_data_refresh_captcha() {
 var i;
 for (i in this.controls) {
  if (document.getElementById('mvote_register'+this.controls[i]).style.display=='block') {
   buttons_state(this.controls[i],false);
   document.getElementById('mvote_captcha_img'+this.controls[i]).src=mvote_captcha;
  }
 }
}

//Links control with model
function vcontrol_data_addlink(control) {
 this.controls[this.controls.length]=control;
 this.update(control);
}

//Loads control model
function vcontrol_data_load() {
 var options={module: 'votecontrol', action: 'getCurrentVotes', forumName: this.forum, url: this.url};
 var func=function(req) {
  if (req.responseJS.errorCode==0) {
   //Setup login/session variables
   mvote_is_login=req.responseJS.data.loggedIn==1;
   mvote_user=mvote_is_login?req.responseJS.data.userName:'';
   mvote_collector_full_url=mvote_collector_url+';jsessionid='+req.responseJS.data.sessionId;
   d=new Date();
   d.setTime(d.getTime()+mvote_cookie_time);
   document.cookie='marketocracy_sid='+req.responseJS.data.sessionId+';expires='+d.toGMTString()+'; path=/';
   //Update captcha to new session id
   update_captcha();
   //Update model
   req.model.avg_rate=req.responseJS.data.value;
   req.model.avg_count=req.responseJS.data.count;
   req.model.rate=req.responseJS.data.yourVote;
   req.model.tags=req.responseJS.data.tags;
   req.model.active=true;
   req.model.loaded=true;
   req.model.is_init=true;
   //Update controls
   req.model.update_all();
   req.model.is_init=false;
  } else {
   //Error
   ajax_error(req.responseJS.error);
  } 
 };
 ajax_request(this,options,func);
}

//Sends model rating
function vcontrol_data_send_vote(vcontrol) {
 this.active_control=vcontrol;
 var options={module: 'votecontrol', action: 'vote', forumName: this.forum, url: this.url, vote: this.rate, topic: mvote_titles[vcontrol]};
 var func=function(req) {
  switch (req.responseJS.errorCode) {
   case 0:
    req.model.rate=req.responseJS.data.yourVote;
    req.model.avg_rate=req.responseJS.data.value;
    req.model.avg_count=req.responseJS.data.count;
    req.model.release();
    break;
   case -1:
    user_logout();
    after_logout(req.model.active_control);
    login_form(req.model.active_control);
    break;
   default:
    req.model.rate='';
    req.model.active=false;
    //Update controls
    req.model.update_all();
    if (req.responseJS.errorCode==3 || req.responseJS.errorCode==4) {
     alert(req.responseJS.error);
    } else {
     ajax_error(req.responseJS.error);
    }
  }
 };
 ajax_request(this,options,func);
}

//Makes voting for control model
function vcontrol_data_vote(rate,vcontrol) {
 this.rate=rate;
 this.use();
 if (mvote_is_login) {
  this.send_vote(vcontrol);
 } else {
  this.is_comment=false;
  login_form(vcontrol);
 } 
}

//Sends comment
function vcontrol_data_send_comment(vcontrol) {
 this.active_control=vcontrol;
 var options={module: 'votecontrol', action: 'submitComment', forumName: this.forum, url: this.url, topic: mvote_titles[vcontrol], tags: document.getElementById('mvote_tags'+vcontrol).value, comment: document.getElementById('mvote_comment'+vcontrol).value};
 var func=function(req) {
  switch (req.responseJS.errorCode) {
   case 0:
    req.model.rate=req.responseJS.data.yourVote;
    req.model.avg_rate=req.responseJS.data.value;
    req.model.avg_count=req.responseJS.data.count;
    comment_btn_state(req.model.active_control,true);
    mvoteCommentCancel(req.model.active_control);
    req.model.release();
    alert(mvote_texts.comment_confirm);
    break;
   case -1:
    user_logout();
    after_logout(req.model.active_control);
    login_form(req.model.active_control);
    break;
   case 5:
    comment_btn_state(req.model.active_control,true);
    req.model.release();
    alert(mvote_texts.tags_error+req.responseJS.error);
    break;
   default:
    req.model.rate='';
    req.model.active=false;
    comment_btn_state(req.model.active_control,true);
    mvoteCommentCancel(req.model.active_control);
    //Update controls
    req.model.update_all();
    if (req.responseJS.errorCode==3 || req.responseJS.errorCode==4) {
     alert(req.responseJS.error);
    } else {
     ajax_error(req.responseJS.error);
    }
  }
 };
 ajax_request(this,options,func);
}

//Makes commenting for control model
function vcontrol_data_comment(vcontrol) {
 comment_btn_state(vcontrol,false);
 this.use();
 if (mvote_is_login) {
  this.send_comment(vcontrol);
 } else {
  this.is_comment=true;
  login_form(vcontrol);
 } 
}

//Login into forum
function vcontrol_data_login(vcontrol) {
 if (mvote_before_login(vcontrol)) {
  this.active_control=vcontrol;
  var options={module: 'votecontrol', action: 'login', username: document.getElementById('mvote_user'+vcontrol).value, password: document.getElementById('mvote_pass'+vcontrol).value};
  var func=function(req) {
   if (req.responseJS.errorCode>0) {
    buttons_state(req.model.active_control,true);
    ajax_error(req.responseJS.error);
   } else {
    if (req.responseJS.errorCode==0) {
     mvote_user=req.login_name;
     if (mvote_is_login) {
      //Repeated login
      after_login(null);
     } else {
      mvote_is_login=true;
      document.getElementById('mvote_login'+req.model.active_control).style.display='none';
      document.getElementById('mvote_register'+req.model.active_control).style.display='none';
      after_login(req.model.active_control);
      if (req.model.is_comment) {
       req.model.send_comment(req.model.active_control);
      } else {
       req.model.send_vote(req.model.active_control);
      } 
     }
     //Call to partner's code jack
     if (req.responseJS.data.associatedUser!=='') {internal_ipbapi_shared_login(req.responseJS.data.uuid);}
    } else {
     buttons_state(req.model.active_control,true);
     alert('Unable to login, please check your user name and password!');
    }
   }
  };
  ajax_request(this,options,func);
  if (!mvote_after_login(vcontrol)) {this.logout();}
 } 
}

//Makes logout
function vcontrol_data_logout() {
 if (mvote_before_logout()) {
  var options={module: 'votecontrol', action: 'logout'};
  var func=function(req) {
   if (req.responseJS.errorCode==0) {
    user_logout();
    after_logout(null);
   } else {
    ajax_error(req.responseJS.error);
   }
  };
  ajax_request(this,options,func);
  if (!mvote_after_logout()) {alert(mvote_texts.msg_err_after_logout);}
 } 
}

//Register new user
function vcontrol_data_register(vcontrol) {
 if (mvote_before_register(vcontrol)) {
  this.active_control=vcontrol;
  var options={module: 'votecontrol', action: 'register', username: document.getElementById('mvote_reg_user'+vcontrol).value, password: document.getElementById('mvote_reg_pass'+vcontrol).value, email: document.getElementById('mvote_reg_email'+vcontrol).value, optin: (mvote_is_optin && document.getElementById('mvote_reg_optin'+vcontrol).checked)?1:0, firstName: document.getElementById('mvote_reg_firstname'+vcontrol).value, lastName: document.getElementById('mvote_reg_lastname'+vcontrol).value, confirmation: email_confirmation};
  if (document.getElementById('captcha_input_line'+vcontrol).style.display=='block') {
   options.captcha=document.getElementById('mvote_reg_captcha'+vcontrol).value;
  }
  var func=function(req) {
   if (req.responseJS.errorCode==0) {
    if (req.responseJS.data.loggedIn==1) {
     mvote_user=req.login_name;
     mvote_is_login=true;
     document.getElementById('mvote_login'+req.model.active_control).style.display='none';
     document.getElementById('mvote_register'+req.model.active_control).style.display='none';
     after_login(req.model.active_control);
     if (req.model.is_comment) {
      req.model.send_comment(req.model.active_control);
     } else {
      req.model.send_vote(req.model.active_control);
     } 
     //Call to partner's code jack
     if (req.responseJS.data.associatedUser!=='') {internal_ipbapi_shared_login(req.responseJS.data.uuid);}
    } else {
     document.getElementById('mvote_user'+req.model.active_control).value=req.login_name;
     login_form(req.model.active_control);
    }
    alert(req.responseJS.data.message);
   } else {
    alert(req.responseJS.error);
    if (req.responseJS.errorCode==-4) {
     //registration is prohibited
     document.getElementById('mvote_register'+req.model.active_control).style.display='none';
     document.getElementById('mvote_login'+req.model.active_control).style.display='block';
    }
   }
   //Updates captcha source
   update_captcha();
  };
  ajax_request(this,options,func);
  if (!mvote_after_register(vcontrol)) {alert(mvote_texts.msg_err_after_register);}
 } 
}

//Captures control data model for further usage
function vcontrol_data_use() {
 this.inuse=true;
 this.update_all();
}

//Releases data model for further interactions
function vcontrol_data_release() {
 this.inuse=false;
 this.update_all();
}

//Validates control objects list for specific object, returns -1 if not found or object index in other case
function check_control_obj(forum,url) {
 result=-1;
 for (i in mvote_objects) {
  if (mvote_objects[i].forum==forum && mvote_objects[i].url==url) {
   result=i;
   break;
  }
 }
 return result;
}

//Creates vote control data model object or just link new control if the model exists
function create_vcontrol_model(forum,url,control) {
 var vote_model;
 num=check_control_obj(forum,url);
 if (num==-1) {
  vote_model=new vcontrol_data(forum,url);
  //Adds to global objects list
  mvote_objects[mvote_objects.length]=vote_model;
  //Load model
  vote_model.load();
 } else {
  vote_model=mvote_objects[num];
 }
 mvote_controls[control]=vote_model;
 vote_model.addlink(control);
}

//Add vote control to a page
function vote_control(forum,url,title) {
 var domain, i;
 var mvote_count=mvote_controls.length;
 if (mvote_count==0) {mvote_count++;}
 //For first control only
 if (mvote_count==1) {
  //Caching images
  for (i=0;i<5;i++) {
   img_buf=new Image();
   img_buf.src=mvote_images_path+mvote_images_disabled_off[i];
   img_buf=new Image();
   img_buf.src=mvote_images_path+mvote_images_disabled_on[i];
   img_buf=new Image();
   img_buf.src=mvote_images_path+mvote_images_active_off[i];
   img_buf=new Image();
   img_buf.src=mvote_images_path+mvote_images_active_on[i];
   img_buf=new Image();
   img_buf.src=mvote_images_path+mvote_images_inactive_on[i];
  }
  //Opt-in domains processing
  domain=document.location.hostname;
  for (i in mvote_optin_domains) {
   if (mvote_optin_domains[i]==domain) {
    mvote_is_optin=true;
    break;
   }
  }
 }
 //Outputs control tags
 document.write('<div class="mvotecontrol"><div class="mvotelogo"><img src="'+mvote_logo+'" alt="'+mvote_texts.logo_title+'" width="'+mvote_logo_size.x+'" height="'+mvote_logo_size.y+'" border="0" align="left"></div><div class="mvoteloader" id="mvote_loader'+mvote_count+'">'+mvote_texts.loading+'</div>');
 document.write('<div class="mvoteinfo" id="mvote_info'+mvote_count+'"></div><div class="mvotebar" id="mvote_bar'+mvote_count+'">'+mvote_texts.ratebar_title);
 var i;
 for (i=0;i<7;i++) {
  n=i+1;
  document.write('<img class="mvote_img" src="'+mvote_images_path+mvote_images_inactive_off[i]+'" alt="'+mvote_rate_names[i]+'" title="'+mvote_rate_names[i]+'" width="'+mvote_image_size.x+'" height="'+mvote_image_size.y+'" border="0" id="mvote_img'+mvote_count+'_'+n+'" onMouseOver="mvoteOver('+mvote_count+','+n+');" onMouseOut="mvoteOut('+mvote_count+','+n+');" onClick="mvoteClick('+mvote_count+','+n+');">');
 }
 if (mvote_comment_on) {document.write('<img class="mvote_comment_img" src="'+mvote_images_path+mvote_comment_image+'" alt="'+mvote_texts.comment_alt+'" title="'+mvote_texts.comment_alt+'" width="'+mvote_comment_size.x+'" height="'+mvote_comment_size.y+'" onClick="mvoteCommentClick('+mvote_count+');">');}
 document.write('</div><div class="mvote_login_info" id="mvote_login_info'+mvote_count+'">'+mvote_texts.login_as+'<span id="mvote_login_as'+mvote_count+'"></span>'+mvote_texts.login_info_div+'<a href="javascript: logout('+mvote_count+');">'+mvote_texts.logout+'</a></div>');
 if (mvote_comment_on) {
  document.write('<div class="mvote_comments" id="mvote_comment_area'+mvote_count+'">'+mvote_texts.tags_title+'<input class="mvote_comment_input" type="text" size="20" name="tags" id="mvote_tags'+mvote_count+'" value=""><div class="mvote_tags_info">'+mvote_texts.tags_info+'</div>');
  document.write(mvote_texts.comment_title+'<textarea class="mvote_comment_input" cols="20" rows="'+mvote_comment_rows+'" name="comment" id="mvote_comment'+mvote_count+'"></textarea>');
  document.write('<div class="mvote_comment_buttons"><input class="mvote_comment_send_btn" type="button" value="'+mvote_texts.comment_send_btn_title+'" name="send" id="mvote_comment_sendbtn'+mvote_count+'" onClick="mvoteCommentSend('+mvote_count+');">');
  document.write('<input class="mvote_comment_cancel_btn" type="button" value="'+mvote_texts.comment_cancel_btn_title+'" name="cancel" id="mvote_comment_cancelbtn'+mvote_count+'" onClick="mvoteCommentCancel('+mvote_count+');"></div></div>');
 }
 document.write('<div class="mvotelogin" id="mvote_login'+mvote_count+'"><form>');
 document.write(mvote_texts.user_input_title+'<input class="mvote_input" type="text" size="15" name="user" id="mvote_user'+mvote_count+'" value="">'+mvote_texts.login_inputs_div);
 document.write(mvote_texts.pass_input_title+'<input class="mvote_input" type="password" size="15" name="pass" id="mvote_pass'+mvote_count+'" value="">');
 document.write(mvote_texts.login_btn_div+'<input class="mvote_btn" type="button" value="'+mvote_texts.login_btn_title+'" name="submit" id="mvote_sendbtn'+mvote_count+'" onClick="submit_login('+mvote_count+');">');
 document.write(mvote_texts.cancel_btn_div+'<input class="mvote_btn" type="button" value="'+mvote_texts.cancel_btn_title+'" name="cancel" id="mvote_cancelbtn'+mvote_count+'" onClick="close_login('+mvote_count+');">');
 document.write('<div class="mvotelogin_regtext"><span>or <a href="javascript: register('+mvote_count+');">register</a> if you are a new user</span></div>');
 document.write('</form></div>');
 document.write('<div class="mvoteregister" id="mvote_register'+mvote_count+'"><form>');
 document.write('<div class="mvote_reg_form_line">'+mvote_texts.user_input_title+'<input class="mvote_input" type="text" size="25" name="reg_user" id="mvote_reg_user'+mvote_count+'" value=""></div>');
 document.write('<div class="mvote_reg_form_line">'+mvote_texts.firstname_input_title+'<input class="mvote_input" type="text" size="25" name="reg_firstname" id="mvote_reg_firstname'+mvote_count+'" value=""></div>');
 document.write('<div class="mvote_reg_form_line">'+mvote_texts.lastname_input_title+'<input class="mvote_input" type="text" size="25" name="reg_lastname" id="mvote_reg_lastname'+mvote_count+'" value=""></div>');
 document.write('<div class="mvote_reg_form_line">'+mvote_texts.pass_input_title+'<input class="mvote_input" type="password" size="25" name="reg_pass" id="mvote_reg_pass'+mvote_count+'" value=""></div>');
 if (mvote_retype_password) {document.write('<div class="mvote_reg_form_line">'+mvote_texts.repass_input_title+'<input class="mvote_input" type="password" size="25" name="reg_repass" id="mvote_reg_repass'+mvote_count+'" value=""></div>');}
 document.write('<div class="mvote_reg_form_line">'+mvote_texts.email_input_title+'<input class="mvote_input" type="text" size="25" name="reg_email" id="mvote_reg_email'+mvote_count+'" value=""></div>');
 if (mvote_retype_email) {document.write('<div class="mvote_reg_form_line">'+mvote_texts.remail_input_title+'<input class="mvote_input" type="text" size="25" name="reg_remail" id="mvote_reg_remail'+mvote_count+'" value=""></div>');}
 document.write('<div class="mvote_reg_form_line" id="captcha_input_line'+mvote_count+'">'+mvote_texts.captcha_input_title+'<input class="mvote_input" type="text" size="25" name="reg_captcha" id="mvote_reg_captcha'+mvote_count+'" value=""><div class="mvote_reg_form_captcha_hint">'+mvote_texts.captcha_input_hint.replace('<a>','<a href="javascript: update_captcha();">')+'</div></div>');
 document.write('<div class="mvote_reg_form_captcha" id="captcha_img_line'+mvote_count+'"><img src="" border="0" alt="'+mvote_texts.captcha_alt+'" id="mvote_captcha_img'+mvote_count+'" onload="validate_captcha('+mvote_count+');"></div>');
 if (mvote_is_optin) {document.write('<div class="mvote_reg_form_checkbox"><input type="checkbox" name="reg_optin" id="mvote_reg_optin'+mvote_count+'" value="1"><strong>'+mvote_texts.opt_in_title+'</strong>'+mvote_texts.opt_in_text.replace('<a>','<a href="'+mvote_optin_url+'">')+'</div>');}
 document.write('<div class="mvote_reg_form_buttons"><input class="mvote_btn" type="button" value="'+mvote_texts.register_btn_title+'" name="submit" id="mvote_regbtn'+mvote_count+'" onClick="submit_register('+mvote_count+');">');
 document.write(mvote_texts.cancel_btn_div+'<input class="mvote_btn" type="button" value="'+mvote_texts.cancel_btn_title+'" name="cancel" id="mvote_reg_cancelbtn'+mvote_count+'" onClick="close_login('+mvote_count+');"></div></form>');
 if (mvote_texts.reg_info_text!=='') {document.write('<div class="mvote_reg_info">'+mvote_texts.reg_info_text+'</div>');}
 document.write('</div></div>');
 //Reset comment field
 if (mvote_comment_on) {document.getElementById('mvote_comment'+mvote_count).value='';}
 //Creates control model
 if (url=='') {url=document.URL;}
 if (title=='') {title=document.title;}
 mvote_titles[mvote_count]=title;
 create_vcontrol_model(forum,url,mvote_count);
}

//Image mouse over handler
function mvoteOver(vcontrol,vote_val) {
 if (mvote_controls[vcontrol].active && !mvote_controls[vcontrol].inuse) {
  document.getElementById('mvote_img'+vcontrol+'_'+vote_val).src=mvote_images_path+(mvote_controls[vcontrol].rate!=='' && mvote_controls[vcontrol].rate==vote_val-4?mvote_images_active_on[vote_val-1]:mvote_images_active_off[vote_val-1]);
 }
}

//Image mouse out handler
function mvoteOut(vcontrol,vote_val) {
 if (mvote_controls[vcontrol].active && !mvote_controls[vcontrol].inuse) {
  document.getElementById('mvote_img'+vcontrol+'_'+vote_val).src=mvote_images_path+(mvote_controls[vcontrol].rate!=='' && mvote_controls[vcontrol].rate==vote_val-4?mvote_images_inactive_on[vote_val-1]:mvote_images_inactive_off[vote_val-1]);
 }
}

//Image click handler
function mvoteClick(vcontrol,vote_val) {
 var model=mvote_controls[vcontrol];
 if (model.active && !model.inuse) {
  num=vote_val-4;
  model.vote(num,vcontrol);
 }
}

//Activates login form
function login_form(vcontrol) {
 buttons_state(vcontrol,true);
 document.getElementById('mvote_register'+vcontrol).style.display='none';
 document.getElementById('mvote_login'+vcontrol).style.display='block';
}

//Validates login form fields
function validate_form(vcontrol) {
 result=true;
 if (document.getElementById('mvote_user'+vcontrol).value=='') {
  result=false;
  alert(mvote_texts.msg_err_empty_username);
 } else {
  if (document.getElementById('mvote_pass'+vcontrol).value=='') {
   result=false;
   alert(mvote_texts.msg_err_empty_password);
  }
 }
 return result;
}

//Makes login request
function submit_login(vcontrol) {
 buttons_state(vcontrol,false);
 if (validate_form(vcontrol)) {
  mvote_controls[vcontrol].login(vcontrol);
 } else {
  buttons_state(vcontrol,true);
 } 
}

//Makes logout request
function logout(vcontrol) {
 mvote_controls[vcontrol].logout();
}

//Closes login form
function close_login(vcontrol) {
 document.getElementById('mvote_login'+vcontrol).style.display='none';
 document.getElementById('mvote_register'+vcontrol).style.display='none';
 mvote_controls[vcontrol].rate='';
 comment_btn_state(vcontrol,true);
 mvote_controls[vcontrol].release();
}

//Sets buttons state (TRUE = enabled button) for the specific login/registration form
function buttons_state(vcontrol,state) {
 document.getElementById('mvote_sendbtn'+vcontrol).disabled=!state;
 document.getElementById('mvote_cancelbtn'+vcontrol).disabled=!state;
 document.getElementById('mvote_regbtn'+vcontrol).disabled=!state;
 document.getElementById('mvote_reg_cancelbtn'+vcontrol).disabled=!state;
}

//Sets comment buttons state (TRUE = enabled button) for the specific control
function comment_btn_state(vcontrol,state) {
 if (mvote_comment_on) {document.getElementById('mvote_comment_cancelbtn'+vcontrol).disabled=!state;}
}

//Reloads data models state (vcontrol model will be skipped if specified)
function reload_models(vcontrol) {
 var i,j;
 var model=vcontrol===null?null:mvote_controls[vcontrol];
 //Updates data models for new login state
 for (i in mvote_objects) {
  if (mvote_objects[i]!==model) {
   //Hide all login and registration forms
   for (j in mvote_objects[i].controls) {
    document.getElementById('mvote_login'+mvote_objects[i].controls[j]).style.display='none';
    document.getElementById('mvote_register'+mvote_objects[i].controls[j]).style.display='none';
   }
   //Reset and reload model
   mvote_objects[i].rate='';
   mvote_objects[i].active=false;
   mvote_objects[i].inuse=false;
   mvote_objects[i].update_all();
   mvote_objects[i].loaded=false;
   mvote_objects[i].load();
  }
 }
}

//Clear form fields for all forms
function clear_forms() {
 var i,j;
 //Lookup all data models
 for (i in mvote_objects) {
  //Cleanup forms
  for (j in mvote_objects[i].controls) {
   //Clear login form
   document.getElementById('mvote_user'+mvote_objects[i].controls[j]).value='';
   document.getElementById('mvote_pass'+mvote_objects[i].controls[j]).value='';
   //Clear registration form
   document.getElementById('mvote_reg_user'+mvote_objects[i].controls[j]).value='';
   document.getElementById('mvote_reg_firstname'+mvote_objects[i].controls[j]).value='';
   document.getElementById('mvote_reg_lastname'+mvote_objects[i].controls[j]).value='';
   document.getElementById('mvote_reg_pass'+mvote_objects[i].controls[j]).value='';
   if (mvote_retype_password) {document.getElementById('mvote_reg_repass'+mvote_objects[i].controls[j]).value='';}
   document.getElementById('mvote_reg_email'+mvote_objects[i].controls[j]).value='';
   if (mvote_retype_email) {document.getElementById('mvote_reg_remail'+mvote_objects[i].controls[j]).value='';}
   document.getElementById('mvote_reg_captcha'+mvote_objects[i].controls[j]).value='';
   if (mvote_is_optin) {document.getElementById('mvote_reg_optin'+mvote_objects[i].controls[j]).checked=false;}
  }
 }
}

//Makes actions needed after login, vcontrol - source control
function after_login(vcontrol) {
 clear_forms();
 reload_models(vcontrol);
}

//Makes actions needed after logout, vcontrol - source control
function after_logout(vcontrol) {
 reload_models(vcontrol);
 if (vcontrol!==null) {mvote_controls[vcontrol].update_all();}
}

//Opens registration form
function register(vcontrol) {
 document.getElementById('captcha_input_line'+vcontrol).style.display='none';
 document.getElementById('captcha_img_line'+vcontrol).style.display='block';
 buttons_state(vcontrol,false);
 document.getElementById('mvote_login'+vcontrol).style.display='none';
 document.getElementById('mvote_register'+vcontrol).style.display='block';
 document.getElementById('mvote_captcha_img'+vcontrol).src=mvote_captcha;
}

//Validates registration form fields
function validate_reg_form(vcontrol) {
 result=true;
 if (document.getElementById('mvote_reg_user'+vcontrol).value=='') {
  result=false;
  alert(mvote_texts.msg_err_empty_username);
 } else {
  if (document.getElementById('mvote_reg_firstname'+vcontrol).value=='') {
   result=false;
   alert(mvote_texts.msg_err_empty_firstname);
  } else {
   if (document.getElementById('mvote_reg_lastname'+vcontrol).value=='') {
    result=false;
    alert(mvote_texts.msg_err_empty_lastname);
   } else {
    if (document.getElementById('mvote_reg_pass'+vcontrol).value=='') {
     result=false;
     alert(mvote_texts.msg_err_empty_password);
    } else {
     if (mvote_retype_password && document.getElementById('mvote_reg_pass'+vcontrol).value!=document.getElementById('mvote_reg_repass'+vcontrol).value) {
      result=false;
      alert(mvote_texts.msg_err_retype_password);
     } else {
      if (document.getElementById('mvote_reg_email'+vcontrol).value=='') {
       result=false;
       alert(mvote_texts.msg_err_empty_email);
      } else {
       if (mvote_retype_email && document.getElementById('mvote_reg_email'+vcontrol).value!=document.getElementById('mvote_reg_remail'+vcontrol).value) {
        result=false;
        alert(mvote_texts.msg_err_retype_email);
       } else {
        if (document.getElementById('captcha_input_line'+vcontrol).style.display=='block' && document.getElementById('mvote_reg_captcha'+vcontrol).value=='') {
         result=false;
         alert(mvote_texts.msg_err_empty_captcha);
        }
       } 
      }
     }
    } 
   }
  } 
 }
 return result;
}

//Submit registration data
function submit_register(vcontrol) {
 buttons_state(vcontrol,false);
 if (validate_reg_form(vcontrol)) {
  mvote_controls[vcontrol].register(vcontrol);
 } else {
  buttons_state(vcontrol,true);
 }
}

//Updates catcha source for all forms
function update_captcha() {
 var i,d=new Date();
 mvote_captcha=mvote_collector_full_url+'?module=votecontrol&action=captcha&timestamp='+d.getTime();
 for (i in mvote_objects) {
  mvote_objects[i].refresh_captcha();
 }
 if (mvote_captcha_listener!==null) {mvote_captcha_listener();}
}

//Validates captcha after loading
function validate_captcha(vcontrol) {
 var img=document.getElementById('mvote_captcha_img'+vcontrol);
 document.getElementById('captcha_input_line'+vcontrol).style.display=(img.width==1 && img.height==1)?'none':'block';
 document.getElementById('captcha_img_line'+vcontrol).style.display=(img.width==1 && img.height==1)?'none':'block';
 buttons_state(vcontrol,true);
}

//Processes comment button click (turn on/off commenting for voting)
function mvoteCommentClick(vcontrol) {
 if (mvote_comment_on) {
  var comments=document.getElementById('mvote_comment_area'+vcontrol);
  comments.style.display=comments.style.display=='block'?'none':'block';
 } 
}

//Cancel comment input
function mvoteCommentCancel(vcontrol) {
 if (mvote_comment_on) {document.getElementById('mvote_comment_area'+vcontrol).style.display='none';}
}

//Validate comment fields
function mvoteValidateComment(vcontrol) {
 var comment=document.getElementById('mvote_comment'+vcontrol);
 var result=comment.value!=='';
 if (!result) {
  alert(mvote_texts.empty_comment_error);
  comment.focus();
 }
 return result;
}

//Send comment
function mvoteCommentSend(vcontrol) {
 var model=mvote_controls[vcontrol];
 if (model.active && !model.inuse) {
  if (mvoteValidateComment(vcontrol)) {
   model.comment(vcontrol);
  } 
 }
}

//Handles comment field input
function mvoteCommentChange(vcontrol) {
 var comment=document.getElementById('mvote_comment'+vcontrol);
 while (comment.offsetHeight<comment.scrollHeight) {comment.rows++;}
}
