﻿var timerID = 0;
var poll_period = 10000;
var local_refresh_counter=0;
var ajax_timeouts=0;
var ajax_errors=0;
var polling_refresh_id = setInterval ( "refresh_sidebar()", 15000 );

function start_ajax() 
{
    update_timer();
    return true;
}



// -----------------------------------------------------------------------------
function update_timer()
{
 refresh_sidebar();
// timerID = setTimeout("update_timer()", poll_period);
}
// -----------------------------------------------------------------------------
function calendar(input_name){
    $(input_name).datepicker({dateFormat: 'dd/mm/yy',maxDate: '+3m',minDate: '+1d',beforeShowDay: $.datepicker.noWeekends,altField: '#alternate' });   
}



function calendar(input_name,mindate){
    $(input_name).datepicker("destroy");
    $(input_name).datepicker({dateFormat: 'dd/mm/yy',maxDate: '+3m',minDate: mindate,beforeShowDay: $.datepicker.noWeekends,altField: '#alternate' });   
}


function OnTimeOut(arg)
{
    //alert("OnTimeOut()" + arg);
    ajax_timeouts++;
}
// -----------------------------------------------------------------------------

function parsedate_UK(s_UK)
{
  var A = s_UK.split(/[\\\/]/); 
      A = [A[1],A[0],A[2]];
  var D = new Date(A.join('/'));
 // alert('D' + D.toString());
  return D; 
} 

function set_readonly(field){
  $(field).attr("disabled","disabled");
  $(field).addClass("disabled");
}

function OnError(arg)
{
//    alert("OnError()"+arg);
    ajax_errors++;
}


var sidebar_sent = 0;
var init_local_refresh = 0;
// -----------------------------------------------------------------------------
function refresh_sidebar()
{
        local_refresh_counter=3;
        
        if ( init_local_refresh == 0 ){
           init_local_refresh = 1;    
           local_refresh();
        }
 
        if (sidebar_sent == 0){
            sidebar_sent = 1;
            mmcode.get_sidebar_data( OnComplete_sidebar_data, OnTimeOut, OnError);
        }
    return true;
}


// -----------------------------------------------------------------------------
function OnComplete_sidebar_data(arg)
{
     
    if (arg.valid_data==1)
    {
    
    var Selling = "";
    var Buying = "";
    var Questions = "";         

    
        Selling  += "<p ><a class='grey' href='/my_stock'>" + arg.selling_items + " Selling Items </a></p>";
        Selling  += "<p ><a class='" + arg_alertcolor(arg.selling_active_bids) + "' href='/my_mostmetals/?tab=selling&filter=1'>" + arg.selling_active_bids  + " Accept or Reject</a></p>";
        if(arg.selling_accepted != 0)    Selling  += "<p ><a class='grey' href='/my_mostmetals/?tab=selling&filter=2'>" + arg.selling_accepted + " Awaiting Delivery Details</a></p>";
        if(arg.selling_payment != 0)    Selling  += "<p ><a class='grey' href='/my_mostmetals/?tab=selling&filter=4'>" + arg.selling_payment + " Awaiting Payment from Buyer</a></p>";
        if(arg.selling_shipment != 0)    Selling  += "<p ><a class='" + arg_alertcolor(arg.selling_shipment) + "' href='/my_mostmetals/?tab=selling&filter=5'>" + arg.selling_shipment + " Awaiting Shipment </a></p>";
        if(arg.selling_ok != 0)    Selling  += "<p ><a class='grey' href='/my_mostmetals/?tab=selling&filter=6'>" + arg.selling_ok +" Awaiting OK  <a/></p>";
        if(arg.seller_dispute != 0)      Selling  += "<p ><a class='alerttext' href='/my_mostmetals/?tab=selling&filter=9'>" + arg.seller_dispute +" In Dispute  <a/></p>";
        if(arg.seller_dispute_resolved != 0)      Selling  += "<p ><a class='grey' href='/my_mostmetals/?tab=selling&filter=10'>" + arg.seller_dispute_resolved +" Dispute Resolved <a/></p>";
        if(arg.awaiting_payment_MM != 0)      Selling  += "<p ><a class='grey' href='/my_mostmetals/?tab=selling&filter=7'>" + arg.awaiting_payment_MM +" MM to pay<a/></p>";
      
        Selling  += "<p ><a class='grey' href='/my_mostmetals/?tab=completed'>" + arg.selling_completed + " Completed </a></p>";

        Buying  += "<p ><a class='grey' href='/my_mostmetals/?tab=buying&filter=1'>" +  arg.buying_active_bids  + " Active Bids </a></p>";
        if(arg.buying_accepted != 0)    Buying  += "<p ><a class='" + arg_alertcolor(arg.buying_accepted) + "' href='/my_mostmetals/?tab=buying&filter=2'>" + arg.buying_accepted +" Awaiting Delivery Details   <a/></p>";
        if(arg.buying_payment != 0)     Buying  += "<p ><a class='" + arg_alertcolor(arg.buying_payment) + "' href='/my_mostmetals/?tab=buying&filter=4'>" + arg.buying_payment +" Awaiting Payment  <a/></p>";
        if(arg.buying_shipment != 0)    Buying  += "<p ><a class='grey' href='/my_mostmetals/?tab=buying&filter=5'>" + arg.buying_shipment +" Awaiting Shipment  <a/></p>";                
        if(arg.buying_ok != 0)          Buying  += "<p ><a class='alerttext' href='/my_mostmetals/?tab=buying&filter=6'>" + arg.buying_ok +" Awaiting OK  <a/></p>";                
        if(arg.buyer_dispute != 0)      Buying  += "<p ><a class='alerttext' href='/my_mostmetals/?tab=buying&filter=9'>" + arg.buyer_dispute +" In Dispute  <a/></p>";
        if(arg.buyer_dispute_resolved != 0)      Buying  += "<p ><a class='grey' href='/my_mostmetals/?tab=buying&filter=10'>" + arg.buyer_dispute_resolved +" Dispute Resolved <a/></p>";
        
        Buying  += "<p ><a class='grey' href='/my_mostmetals/?tab=completed'>" + arg.buying_completed +" Completed <a/></p>";
        
        Questions  += "<p ><a class='grey' href='/my_mostmetals/?tab=questions&filter=1'>" +  arg.questions_youasked  + " You Asked </a></p>";
        Questions  += "<p ><a class='grey' href='/my_mostmetals/?tab=questions&filter=4'>" +  arg.questions_theyasked  + "  They Asked </a></p>";
       if (arg.questions_theyaskedunans != 0) Questions  += "<p ><a class='alerttext' href='/my_mostmetals/?tab=questions&filter=2'>" +  arg.questions_theyaskedunans  + " You need to answer</a></p>";
       if (arg.questions_youaskedans  != 0) Questions  += "<p ><a class='grey' href='/my_mostmetals/?tab=questions&filter=6'>" +  arg.questions_youaskedans  + "  You Asked Answered</a></p>";
         
       $('#dv_selling_items').html( Selling.toString());
       $('#dv_buying_items').html( Buying.toString());
       $('#dv_questions_items').html( Questions.toString());
    }
    sidebar_sent = 0;
}

function arg_alertcolor(arg){
    if (arg > 0){
        return  "alerttext";
    }
    return "grey"; 
}




// ----------------------------------------------------------------------------------------------
function _empty_select( object_id )
{
    var object_selected = document.getElementById(object_id);
     for (var i=(object_selected.options.length-1); i>=0; i--) { 
		object_selected.options[i] = null; 
		} 
	object_selected.selectedIndex = -1; 
}
// ----------------------------------------------------------------------------------------------
function _add_select_item( object_id, id, text)
{
    ele = text.toString();
    if (ele.length>0)
    {
    
        var object_selected = document.getElementById(object_id);
        if (object_selected)
        {
            var elOptNew = document.createElement('option');
            elOptNew.text = ele;
            elOptNew.value = id
            try 
            {
                object_selected.add(elOptNew, null); // standards compliant; doesn't work in IE
            }
            catch(ex) 
            {
                object_selected.add(elOptNew); // IE only
            }
    
        }
  //        object_selected.add(new Option(text,id));
    }
}

function pause(millis)
{
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < millis);
}

// ----------------------------------------------------------------------------------------------
function _object_value( object_id)
{
     var object_selected = document.getElementById(object_id);
     var rc =object_selected.value;
     return rc;
}
// ----------------------------------------------------------------------------------------------
function _set_object_value( object_id,_value)
{
     var object_selected = document.getElementById(object_id);
     var rc =object_selected.value = _value;
}
// ----------------------------------------------------------------------------------------------
function _set_object_inner_html( object_id,_value)
{
     var object_selected = document.getElementById(object_id);
     var rc =object_selected.innerHTML = _value;
}
// ----------------------------------------------------------------------------------------------
function _set_object_src( object_id,_value)
{
     var object_selected = document.getElementById(object_id);
     var rc =object_selected.src = _value;
}
// ----------------------------------------------------------------------------------------------
function _cb_value( object_id)
{
     var object_selected = document.getElementById(object_id);
     var rc =0;
     if (object_selected.checked)
      rc=1;
     return rc;
}
// ----------------------------------------------------------------------------------------------
function _cb_bool_value( object_id)
{
     var object_selected = document.getElementById(object_id);
     var rc =false;
     if (object_selected.checked)
      rc=true;
     return rc;
}
// ----------------------------------------------------------------------------------------------
function _cb_checked( object_id)
{
     var object_selected = document.getElementById(object_id);
     var rc =object_selected.checked;
     return rc;
}
// ----------------------------------------------------------------------------------------------
function _set_cb_checked( object_id,_value)
{
     var object_selected = document.getElementById(object_id);
     object_selected.checked = _value;
}
// ----------------------------------------------------------------------------------------------
function _set_object_classname( object_id,class_name)
{
     var object_selected = document.getElementById(object_id);
     object_selected.className = class_name;
}
// ----------------------------------------------------------------------------------------------
function _display_object( object_id, visible)
{
     var object_selected = document.getElementById(object_id);
     var rc;
     if (visible)
        rc=object_selected.style.display =  'inline';
     else
        rc=object_selected.style.display = 'none';
     return rc;
}
// ----------------------------------------------------------------------------------------------
function _set_object_visible( object_id,view_state)
{
     var object_selected = document.getElementById(object_id);
     if (view_state==false)
         object_selected.style.visibility='hidden';
     else
         object_selected.style.visibility='visible';
}
// ----------------------------------------------------------------------------------------------
function email_validation(str) {
// validation check for emails

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }
 		 return true					
	}

// ----------------------------------------------------------------------------------------------
function load_picture( object_id, pic_url)
{
        var object_selected = document.getElementById(object_id);
        object_selected.innerHTML = "<a href='" + pic_url + "' class='thickbox' rel='gallery-product' title=''> <img src='" +  pic_url +  "' /> </a>" ;
}

function load_picture_class( object_id, pic_url)
{
        $("."+object_id).html("<a href='" + pic_url + "' class='thickbox' rel='gallery-product' title=''> <img src='" +  pic_url +  "' /> </a>" );   
}

function load_inactive_picture( object_id, pic_url)
{
 
   
     var object_selected = document.getElementById(object_id);
     object_selected.innerHTML = "<img src='" +  pic_url +  "' /> " ;
   
}

function length_check(msg) {
  
   if ( msg.length > 0 ){
      return true;
   }
   
   return false;
}

function price_round ( price_input ){
 try {
    
     var price  = price_input.value
     //set rounding to 2 dp
     bid = Math.round((price)*100)/100; 
     // Only postive Numbers
     bid = Math.abs(bid);
     price_input.value = bid;
     if(isNaN(parseFloat(bid))){
         price_input.value = 0;
     }
 }
 catch(err) {
    price_input.value = 0;
 }
    
}

function price_round_neg ( price_input ){
 try {
    
     var price  = price_input.value
     //set rounding to 2 dp
     bid = Math.round((price)*100)/100; 
     // Only postive Numbers
     //bid = Math.abs(bid);
     price_input.value = bid;
     if(isNaN(parseFloat(bid))){
         price_input.value = 0;
     }
 }
 catch(err) {
    price_input.value = 0;
 }
    
}

function int_round ( price_input ){
  
 var price  = price_input.value
 //set rounding to 0 dp
 var bid = Math.round(price); 
 // Only postive Numbers
 bid = Math.abs(bid);
 if (isNaN(bid)) {
     bid = 0;
 }
 
 price_input.value = bid;

}

function int_round_neg ( price_input ){
  
 var price  = price_input.value
 //set rounding to 0 dp
 var bid = Math.round(price); 
 // Only postive Numbers
 //bid = Math.abs(bid);
 if (isNaN(bid)) {
     bid = 0;
 }
 
 price_input.value = bid;

}

function cms_popup(page ,section)
{
    mmcode.cms_get_html(page +'|'+section,OnComplete_cms_popup);
}
function OnComplete_cms_popup(arg)
{

  if (arg.html_checksum==1)
  {
 
    show_popup("Help" ,arg.html_data );  
  }
}

function show_popup(title,content) {
    $('#modal_popuptitle').html('<h2>'+title+'</h2>');
    $('#modal_popupcontent').html('' + content);
    show_modal('mpe_modal');
}


function hide_popup() {
    pause(1500);
    document.getElementById('modal_popuptitle').innerHTML = '';
    document.getElementById('modal_popupcontent').innerHTML = '';
    hide_modal('mpe_modal');
}



// ----------------------------------------------------------------------------------------------
function show_modal( object )
{
     var modal = $find(object);
     if (modal)
        modal.show();
     else
        alert('Cannot find '+object);
}
// ----------------------------------------------------------------------------------------------
function hide_modal( object )
{
     var modal = $find(object);
     if (modal)
        modal.hide();
     else
        alert('Cannot find '+object);
}


// ----------------------------------------------------------------------------------------------

function get_date_str (datetime){
// Returns date from SQL DateTime String
    return datetime = datetime.substring(0, 11);
}

function reset_error_lable(lable){
  $(lable).parent().slideUp("fast");        
}

function slideDown(lable){
  $(lable).slideDown("fast");        
}

function modal_error_lable(lable,msg){
        
        $(lable).text(msg);
        $(lable).parent().slideDown("fast").scrollTo(1000);
        $(lable).slideDown("slow");
}

function error_lable(lable,msg){
        
        $(lable).slideUp("fast").animate( { backgroundColor: 'red' }, 300);
        $(lable).parent().slideUp("fast");
        $(lable).text(msg);
        $(lable).parent().slideDown("fast").scrollTo(1000);
        $(lable).slideDown("slow").animate( { backgroundColor: '#fcfcfc' }, 300);
}

function flash_lable(lable,msg,flashcolor,bckgrndcolor,forecolor){
       
        $(lable).text("").scrollTo(1000).parent().slideUp("fast");
        $(lable).animate( { backgroundColor: flashcolor }, 300);
               
        $(lable).parent().slideDown("fast");
        $(lable).animate( { backgroundColor: bckgrndcolor }, 300);
        $(lable).text(msg);
        $(lable).attr( 'style', 'color:'+forecolor );
        }
        
function clear_text( input ){
  alert('asd');
 input.value = "";

} 

