//SKRIPTA ZA PUNJENJE VEZANIH BOX-eva
function box2click(content) {
  $("#box2_"+content+"_scrollboxInner td").not(".graph").not(".mark").click(function(){   
    $("#box2 tr").removeClass("active");
		$(this).parents("tr").addClass("active");
		view1ticker = $(this).parents("tr").children(".name").children("span").text();
		$("#box3 .inner > div object").remove();
		$("#box3 .inner > div").html("");
		$("#box4 .inner > div").html("");
		switch ($("#box3 .boxnav .on").attr("id")) {
      case "box3_link1":
          graphBox3(view1ticker);
        break;
      case "box3_link2":
          sentimentInt(view1ticker);          
        break;
      case "box3_link3":
          newsBox3(view1ticker);
        break;    
    }
    switch ($("#box4 .boxnav .on").attr("id")) {
      case "box4_link1":
          basicBox4(view1ticker);
        break;
      case "box4_link2":
          fundamentBox4(view1ticker);
        break;
      case "box4_link3":
          tehnicalBox3(view1ticker);
        break;
      case "box4_link4":
          analBox3(view1ticker);
        break;    
    }		
	});
}

//UBACIVANJE STRELICE ZA LOGIN KOD MANJE REZOLUCIJE
$(document).ready(function() {
    if(scrRes=="small"){
        $("#header").after('<img src="'+urlRoot+'images/logButton.gif" alt="Prijavite se na Investa.hr" title="Prijavite se na Investa.hr" id="logTempButt" />');
        $("#logTempButt").toggle(
            function(){
                $pageDimensions=pageDimensions();
                var scrollAmount = $pageDimensions[1] - $(window).width();
                $("html, body").animate({scrollLeft:scrollAmount}, 200);
                $("#logTempButt").attr("src",""+urlRoot+"images/logButtonBack.gif");
            },
            function(){
                $("html, body").animate({scrollLeft:0}, 200);
                $("#logTempButt").attr("src",""+urlRoot+"images/logButton.gif");
            }
        ); 
    }
});


//SKRIPTA ZA LOADANJE BOXA 1 SLIDEDOWN U BOXU 1
$(document).ready(function() {
  var so = new SWFObject(urlRoot+"flash/brzinomjer.swf?SRVROOT="+urlRoot, "flash_tacho", "266", "122", "9");
  so.addParam("wmode", "transparent");
  so.write("flash_tacho");
  
  var so = new SWFObject(urlRoot+"flash/GraphCrobex.swf?siteURL="+urlRoot+"&period=3", "flash_graph", "260", "155", "9");
  so.addParam("wmode", "transparent");
  so.write("flash_graph");
  
	$("#box1 .boxnav li").click(function() {
		if ( $(this).is("#box1_link1") ) {
		    if ( $("#box1_content1 > .popup").is(":visible") ) {
			    $("#box1_content1 > .popup").hide();
			    return false;
			}
		    if ( $(this).is(".on") ) {
				$("#box1_content1 > .popup").show();
				function infraTimer () {
					window.setTimeout(function() {
					if ( $("#box1_content1 > .popup").is(".on") ) { return; }
					else {
						$("#box1_content1 > .popup").hide();
						$("#box1_link1").unbind("mouseover");
					}
					}, 500);
				}
				$("#box1_link1").mouseout(function(){
				    infraTimer ();
					$("#box1_content1 > .popup").mouseout(function(){
		               	$("#box1_content1 > .popup").removeClass("on");
		               	infraTimer ();
				    }).mouseover(function(){
				        $("#box1_content1 > .popup").addClass("on");
				    });
					$("#box1_content1 > .popup").removeClass("on");
			    }).mouseover(function(){
			        $("#box1_content1 > .popup").addClass("on");
		            $("#box1_content1 > .popup").show();
			    });
			}

			if ( $(this).is(".on") ) {
				return false;
			} else  {
			    if ( $("#box1_content1").html() == false ) {
					$("#box1_content1").show();					
					$("#box1_content1").append("<img src='images/preloader.gif' class='ajax_preloader' alt='' />");
					$.get(urlRoot+"index.php?page=stockView1Box1Content&content=2", function(data){
						$("#box1_content1").html(data);
						$("#box1_content1 input[type=checkbox]").checkbox();
						box1grid();
						//******************* ONCLICK ON POPUP ********************
          	$("#box1 .popup li").click(function(){
                switch ( $(this).attr("class") ){
                    case "all":
                        $("#box1allStocks").show();
                        $("#box1 .popup li a").removeClass("on");
                        $(this).children("a").addClass("on");
                        break;
                    case "active":
                        $("#box1allStocks").hide();
                        $("#box1 .popup li a").removeClass("on");
                        $(this).children("a").addClass("on");
                        break;
                }
                $("#box1_content1 > .popup").hide();
                $("#box1_content1 > .popup").removeClass("on");
            });
						//******************* FULL NAMES ********************
						$("#full_names").click(function() {
						    if ( $("#box1_content1 table").is(".show_names") ) {
								$("#box1_content1 .ticker span").css("display","none");
							    $("#box1_content1 table").removeClass("show_names");
							} else {
							    $("#box1_content1 .ticker span").css("display","block");
							    $("#box1_content1 table").addClass("show_names");
							}
						});
					});

    		    } else {
					$("#box1_content1").show();
				}
				$("#box1_content2").hide();
			}
			$("#box1 .boxnav li").removeClass('on');
            $(this).addClass('on');
		} else  {
        	if ( $(this).is(".on") ) {
				return false;
			} else  {
			    $("#box1_content1").hide();
				$("#box1_content2").show();
			}
			$("#box1 .boxnav li").removeClass('on');
        	$(this).addClass('on');
        }
	});
});




//BOX2
var scrollAmount = 0;
var scrollAmount = new Array(4);
scrollAmount[0]= 0;
scrollAmount[1]= 0;
scrollAmount[2]= 0;
scrollAmount[3]= 0;

function tblSorter(tblName,trigger) {
 	$(tblName).tablesorter({ 
      headers: {
          2: { sorter:'investaNum' },
          3: { sorter:'investaPrecent' },
          4: { sorter:'investaNum' },
          5: { sorter:'investaNum' },
          6: { sorter:'investaNum' },
          7: { sorter:'investaNum' },
          8: { sorter:'investaNum' },
          9: { sorter:'investaNum' }
      } 
  }); 
 	$(tblName).trigger("update");
	var colLength = ( $(tblName+" col").length );
	for (i=1;i<=colLength;i++) {
		$(trigger+i).toggle(
			function () {
				var calicon = $(this).attr("id");
				var sorting = [[calicon.substring(16),0]];
				$(tblName).trigger("sorton",[sorting]);
				return false;
			},
			function () {
				var calicon = $(this).attr("id");
				var sorting = [[calicon.substring(16),1]];
				$(tblName).trigger("sorton",[sorting]);
				return false;
			}
		);
	}
}

function box2_scrolltable(contentNo) {
	if ( $("#box2_content1_scrollboxInner tbody tr").length <= 9 )  { $("#box2_content1_arrows").hide(); }
	$("#box2_content"+contentNo+"_arrows .down").click(function() {
		if ( $(this).is(".off") ) { return; }
		else {
		  scrollAmount[contentNo-1] = scrollAmount[contentNo-1]+34;
		  if ( scrollAmount[contentNo-1] == (($("#box2_content"+contentNo+"_scrollboxInner tr").length * 34)-340) ) { $("#box2_content"+contentNo+"_arrows .down").addClass("off"); }
		  $("#box2_content"+contentNo+"_arrows .up").removeClass("off");
		  $("#box2_content"+contentNo+"_scrollboxInner table").animate({
		    marginTop: "-"+scrollAmount[contentNo-1]+"px"
		  }, 200 );
		}
	});
	$("#box2_content"+contentNo+"_arrows .up").click(function() {
		if ( $(this).is(".off") ) { return; }
		else  {
		  scrollAmount[contentNo-1] = scrollAmount[contentNo-1]-34;
		  if ( scrollAmount[contentNo-1] == 0 ) { $("#box2_content"+contentNo+"_arrows .up").addClass("off"); }
		  $("#box2_content"+contentNo+"_arrows .down").removeClass("off");
		  $("#box2_content"+contentNo+"_scrollboxInner table").animate({
		    marginTop: "-"+scrollAmount[contentNo-1]+"px"
		  }, 200 );
		}
	});
}

function autocompleteInsert(ticker) {
    if( $("#box2_content1_scrollboxInner tr").is("[rel='"+ticker+"']") || ticker=="unesite naziv ili oznaku" ) { return false; }
    var tickerLocation = urlRoot+"index.php?page=stocksApartBox&ticker="+ticker;
    var tblGridHeight = $("#box2 .box2_scrollbox").height();
    if ( $("#box2_content1_scrollboxInner tbody tr").length == 0 ) {
      $("#box2_nostock").hide();
      $("#box2_stock").show();
      saveNewTicker(34,tickerLocation,ticker);
    } else {
      if ( $("#box2_content1_scrollboxInner tbody tr").length >= 9 ) {
        $("#box2_content1_arrows").show();
        $("#box2_content1 .box2_scrollboxInner").css("height","307px");
        saveNewTicker(tblGridHeight,tickerLocation,ticker);
      } else {
        tblGridHeight = tblGridHeight + 34;
        saveNewTicker(tblGridHeight,tickerLocation,ticker);
      }
    }
}

$(document).ready(function() {
  if ( $("#box2_content1_scrollboxInner tbody tr").length >= 9 ) {
    $("#box2_content1_arrows").show();
    $("#box2_content1 .box2_scrollboxInner").css("height","307px");
	}
 	clearInputs (".ex_stck_drop1");
	tbl_dropdown ("#box2_content1");
	box2_scrolltable ("1");
	box2grid();
	tblSorter("#box2_content1_scrollboxInner table","#box2cont1trigger");
	$("#box2_content1 .ex_stock .ex_stck_drop1").autocomplete(urlRoot+"index.php?page=autocomplete&type=stock&partial=1");
	jQuery("#box2_content1 .ex_stock .ex_stck_drop1").result(function(event, data, formatted) {
    var pattern = new RegExp("<");
    pattern.test(formatted.substring(9,formatted.length));
    autocompleteInsert(RegExp.leftContext);
  });

	$("#box2 .nav li").click(function() {
    if ( $("#box2 img").is(".ajax_preloader") ) { return false; }
		if ( $(this).is(".on") ) {
				return false;
			} if ( $(this).children().is("#box2_link1") ) {
			    $("#box2 .nav li").removeClass('on');
			    $(this).addClass('on');
				$("#box2_content2").hide();
				$("#box2_content3").hide();
				$("#box2_content4").hide();
				$("#box2 .inner").append("<img src='images/preloader.gif' class='ajax_preloader' alt='' />");
				var boxHeight = $("#box2_content1").height();
				$("#box2 .inner").animate({ height: boxHeight}, 600, function(){
				    $("#box2 .inner").css("height","auto");
				    $("#box2 .inner .ajax_preloader").remove();
					$("#box2_content1").show();
				});
			} if ( $(this).children().is("#box2_link2") ) {
			    var bufferHeight = $("#box2 .inner").height();
			    $("#box2 .nav li").removeClass('on');
				$(this).addClass('on');
			    $("#box2_content1").hide();
				$("#box2_content3").hide();
				$("#box2_content4").hide();
			    $("#box2 .inner").css("height",bufferHeight).append("<img src='images/preloader.gif' class='ajax_preloader' alt='' />");
			    if ( $("#box2_content2").html() == false ) {
					$.get(urlRoot+"index.php?page=stockView1Box2Content&content=2", function(data){
					    $("#box2 .inner").animate({ height: 396}, 600, function(){
					        $("#box2_content2").html(data);
							tbl_dropdown("#box2_content2");
							box2_scrolltable ("2");
							over_hover ("#box2_content2_scrollboxInner tr");
							box2click ("content2");
							$("#box2 .inner .ajax_preloader").remove();
							$("#box2_content2").show();
							tblSorter("#box2_content2_scrollboxInner table","#box2cont2trigger");
	                	});
					});
				} else {
				    $("#box2 .inner").animate({ height: 396}, 600, function(){
	                    $("#box2 .inner .ajax_preloader").remove();
						$("#box2_content2").show();
                    });
				}
			} if ( $(this).children().is("#box2_link3") ) {
			    var bufferHeight = $("#box2 .inner").height();
			    $("#box2 .nav li").removeClass('on');
			    $(this).addClass('on');
                $("#box2_content1").hide();
				$("#box2_content2").hide();
				$("#box2_content4").hide();
				$("#box2 .inner").css("height",bufferHeight).append("<img src='images/preloader.gif' class='ajax_preloader' alt='' />");
				if ( $("#box2_content3").html() == false ) {
					$.get(urlRoot+"index.php?page=stockView1Box2Content&content=3", function(data){
					    $("#box2 .inner").animate({ height: 396}, 600, function(){
							$("#box2_content3").html(data);
							tbl_dropdown("#box2_content3");
							box2_scrolltable ("3");
							over_hover ("#box2_content3_scrollboxInner tr");
							box2click ("content3");
							$("#box2 .inner .ajax_preloader").remove();
							$("#box2_content3").show();
							tblSorter("#box2_content3_scrollboxInner table","#box2cont3trigger");
                    	});
					});
				} else {
				    $("#box2 .inner").animate({ height: 396}, 600, function(){
	                    $("#box2 .inner .ajax_preloader").remove();
						$("#box2_content3").show();
                    });
				}
			} if ( $(this).children().is("#box2_link4") ) {
			    var bufferHeight = $("#box2 .inner").height();
			    $("#box2 .nav li").removeClass('on');
			    $(this).addClass('on');
                $("#box2_content1").hide();
				$("#box2_content2").hide();
				$("#box2_content3").hide();
				$("#box2 .inner").css("height",bufferHeight).append("<img src='images/preloader.gif' class='ajax_preloader' alt='' />");
				if ( $("#box2_content4").html() == false ) {
					$.get(urlRoot+"index.php?page=stockView1Box2Content&content=4", function(data){
					    $("#box2 .inner").animate({ height: 396}, 600, function(){
							$("#box2_content4").html(data);
							tbl_dropdown("#box2_content4");
							box2_scrolltable ("4");
							over_hover ("#box2_content4_scrollboxInner tr");
							box2click ("content4");
							$("#box2 .inner .ajax_preloader").remove();
							$("#box2_content4").show();
							tblSorter("#box2_content4_scrollboxInner table","#box2cont4trigger");
                        });
					});
				} else {
                    $("#box2 .inner").animate({ height: 396}, 600, function(){
						$("#box2 .inner .ajax_preloader").remove();
						$("#box2_content4").show();
					});
				}
			}
	});
});

// BOX 3
function graphBox3(ticker) {
  $("#box3_link1").addClass("active");
  $("#box3_content1").show();
  $("#box3_content2").hide();
  $("#box3_content3").hide();
  $("#box3_content1").html("<img src='images/preloader.gif' class='ajax_preloader' alt='' />");
  $.get(urlRoot+"index.php?page=stockView1Box3Content&content=chart&ticker="+ticker, function(data){
    $("#box3_content1").html(data);
    var flashWidth = 435;
    var flashHeight = 222;
    if (scrRes=="small"){
        flashWidth = 351;
        flashHeight = 201;
    }    
    var graphValue = $('#box3_flash').attr('rel').split('|');
    var so = new SWFObject(urlRoot+"flash/Graph.swf?siteURL="+urlRoot+"&graphSize=small&graphType=stock&tickerHtml="+graphValue[0]+"&periodStart="+graphValue[1]+"&periodEnd="+graphValue[2], "small_graph", flashWidth, flashHeight, "9");
    so.addParam("allowScriptAccess", "always");
    so.addParam("wmode", "transparent");
    so.write("box3_flash");
    overallSmallCompareAmount = 0;
    for (i=0;i<insertedSmallGraphs.length;i++){
        insertedSmallGraphs[i]="";
    }
    //FLASH HELP FOR MOUSE ENTER/LEAVE
  	$("#box3_flash").hover(function(){
        document.getElementById("small_graph").mouseEnter();
    }, function(){
        document.getElementById("small_graph").mouseLeave(); 
    });
    $(".timespan li").not("#pickDate").click(function(){
  	    if ( $(this).is(".on") ) { return false; }
        $(".timespan li").removeClass("on");
        $(this).addClass("on");
        var ticker = $('#box3_flash').attr('rel').split('|');
        var loc = urlRoot+"index.php?page=xmlStockHistoricDataInfo&ticker="+ticker[0]+"&period="+$(this).attr("rel");
        $.get(loc, function(data){
            flashMethod("small_graph").changePeriod($(data).find('begindate').text(),$(data).find('enddate').text());
				});
  	});
  	dateRestrictor = $("#pickDate").attr("rel").split("|");
    dateRestrictorMin = dateRestrictor[0].split(".");
    dateRestrictorMax = dateRestrictor[1].split(".");
  	$("#pickDate input").datepicker("destroy");
  	var dateImgtemp;
    if (scrRes=="small"){ dateImgtemp = urlRoot+'images/button/smallGraph_pickDate2.gif';  }
  	else { dateImgtemp = urlRoot+'images/button/smallGraph_pickDate.gif'; }
  	$("#pickDate input").datepicker({
        showOn: 'button', 
        buttonImage: dateImgtemp,
        buttonImageOnly: true,
        minDate: new Date(dateRestrictorMin[2],(dateRestrictorMin[1]-1),dateRestrictorMin[0]),
        maxDate: new Date(dateRestrictorMax[2],(dateRestrictorMax[1]-1),dateRestrictorMax[0])    
    });
    $("#pickDate input").bind("change", function(){
        $(".timespan li").removeClass("on");
        document.getElementById("small_graph").changePeriod($("#pickDate input").attr("value"),dateRestrictorMax.join("."));
  	});
  	smallDropCompare(); 	
  });
}

// INSERTING & REMOVING small(GRAPH COMPARE
var overallSmallCompareAmount = 0;
var insertedSmallGraphs = new Array();

function removeSelectedGraphEl(ticker) {
    if ( ticker=="CROBEX"){ 
        $("#popupCompare input[value='"+ticker+"']").parents("li").show();
    }
    if (ticker.substr(0,3)=="IFI"){
        $("#popupCompare input[value='"+ticker+"']").parents("li").show();
    }    
    overallSmallCompareAmount = overallSmallCompareAmount-1;
    if( insertedSmallGraphs[0]==ticker) {
        insertedSmallGraphs[0]="";
    } else {
        if( insertedSmallGraphs[1]==ticker) {
            insertedSmallGraphs[1]="";
        } else {
            if( insertedSmallGraphs[2]==ticker) {
                insertedSmallGraphs[2]="";
            } else {
                insertedSmallGraphs[3]="";
            }
        }
    }
}

function checkColor(ticker){
    overallSmallCompareAmount = overallSmallCompareAmount+1;
    var colorOrder;
    var color;
    if( typeof(insertedSmallGraphs[0])=="undefined"||insertedSmallGraphs[0]=="" ) {
        insertedSmallGraphs[0]=ticker;
        colorOrder = "0";
        color = "000000";
    } else {
        if( typeof(insertedSmallGraphs[1])=="undefined"||insertedSmallGraphs[1]=="" ) {
            insertedSmallGraphs[1]=ticker;
            colorOrder = "1";
            color = "a81400";
        } else {
            if( typeof(insertedSmallGraphs[2])=="undefined"||insertedSmallGraphs[2]=="" ) {
                insertedSmallGraphs[2]=ticker;
                colorOrder = "2";
                color = "0008a8";
            } else {
                insertedSmallGraphs[3]=ticker;
                colorOrder = "3";
                color = "51105c";
            }
        }
    }
    return color+"|"+colorOrder;
}

function smallDropCompare(){
    clearInputs("#stockCompare");
    clearInputs("#fundCompare");
    $("#stockCompare").autocomplete(urlRoot+"index.php?page=autocomplete");
    $("#fundCompare").autocomplete(urlRoot+"index.php?page=autocomplete&type=fund");
    $("#stockCompare").result(function(event, data, formatted) {
        $("#stockCompare").attr("readonly","readonly");
    });
    $("#fundCompare").result(function(event, data, formatted) {
        var tickerName = formatted.split("</b>");
        $(this).val(tickerName[1]);
        var pattern = new RegExp("<");
        pattern.test(formatted.substring(9,formatted.length));
        var fundTicker = RegExp.leftContext;
        $("#fundCompare").attr("rel",fundTicker);
        $("#fundCompare").attr("readonly","readonly");
    });   
    $("#popupCompare input[type=checkbox]").checkbox();
    $("#popupCompare .close").click(function(){
        $("#popupCompare").hide();
    });
    $("#popupCompare .insert").click(function(){
        if(overallSmallCompareAmount>3){ return false; }
        var ticker1 = $("#stockCompare").val();
        if (ticker1!="Unesite naziv ili oznaku" && ticker1!=""){
            var color = checkColor(ticker1).split("|");
            document.getElementById("small_graph").compare(ticker1,"0x"+color[0],"stock");
        }
        var ticker2 = $("#fundCompare").attr("rel");
        var ticker2val = $("#fundCompare").val();
        if (ticker2val!="Unesite naziv" && ticker2val!=""){
            var color = checkColor(ticker2).split("|");
            document.getElementById("small_graph").compare(ticker2,"0x"+color[0],"fund");
        }
        if ($("#popupCompare input[type=checkbox]:checked").length!=0){
            for (i=0;i<$("#popupCompare input[type=checkbox]:checked").length;i++){
                var color = checkColor($("#popupCompare input[type=checkbox]:checked:eq("+i+")").val()).split("|");
                var indexTicker = $("#popupCompare input[type=checkbox]:checked:eq("+i+")").val();
                var indexType;
                if (indexTicker=="CROBEX") {indexType="market";}
                else {indexType="fund";}
                document.getElementById("small_graph").compare(indexTicker,"0x"+color[0],indexType);
            }
            $("#popupCompare input[type=checkbox]:checked").parents("li").hide();
            $("#popupCompare input[type=checkbox]:checked").parents(".jquery-checkbox-box").removeClass("jquery-checkbox-checked");
            $("#popupCompare input[type=checkbox]:checked").attr("checked", false);
        }
        $("#popupCompare").hide();
        $("#stockCompare").val("Unesite naziv ili oznaku");
        $("#fundCompare").val("Unesite naziv");
    });
}

function sentimentInt(ticker) {
  $("#box3_content1").hide();
  $("#box3_content2").show();
  $("#box3_content3").hide();
  $("#box3_content2").html("<img src='images/preloader.gif' class='ajax_preloader' alt='' />");
  $.get(urlRoot+"index.php?page=stockView1Box3Content&content=sentiment&ticker="+ticker, function(data){
    $("#box3_content2").html(data);
    infraSentPopup ("box3_sent_info","box3");
    infraSentPopup ("box3_sent_info2","box3");
    sentAnimation(ticker);
  });
}

function newsBox3(ticker) {
  $("#box3_content1").hide();
  $("#box3_content2").hide();
  $("#box3_content3").show();
  $("#box3_content3").html("<img src='images/preloader.gif' class='ajax_preloader' alt='' />");
  $.get(urlRoot+"index.php?page=stockView1Box3Content&content=news&ticker="+ticker, function(data){
    $("#box3_content3").html(data);
    news1popup("box3_content3");
  });
}

$(document).ready(function() {
	$("#box3 .boxnav li").click(function() {
		if ( $(this).is(".on") ) {
		    if($(this).is(".active")){
            $("#popupCompare").show();
        }
				return false;
			} if ( $(this).is("#box3_link1") ) {
			    $("#box3 .boxnav li").removeClass('on');
			    $(this).addClass('on');
			    if ( $("#box3_content1").contents("span").is(".noneSelected") ) { return false; }
          if ( $("#box3_content1").html() == false ) { graphBox3( $("#box2 .active").children(".name").children("span").text() ); }
			    else {
            $("#box3_content1").show();
            $("#box3_content2").hide();
            $("#box3_content3").hide();
          }			    
			} if ( $(this).is("#box3_link2") ) {
			    $("#box3 .boxnav li").removeClass('on');
			    $(this).addClass('on');
			    if ( $("#box3_content1").contents("span").is(".noneSelected") ) { return false; }
			    if ( $("#box3_content2").html() == false ) { sentimentInt( $("#box2 .active").children(".name").children("span").text() ); }
			    else {
            $("#box3_content1").hide();
            $("#box3_content2").show();
            $("#box3_content3").hide();
          }
			} if ( $(this).is("#box3_link3") ) {
			    $("#box3 .boxnav li").removeClass('on');
			    $(this).addClass('on');
			    if ( $("#box3_content1").contents("span").is(".noneSelected") ) { return false; }
			    if ( $("#box3_content3").html() == false ) { newsBox3( $("#box2 .active").children(".name").children("span").text() ); }
			    else {
            $("#box3_content1").hide();
            $("#box3_content2").hide();
            $("#box3_content3").show();
          }		    
			}
	});
});

// BOX 4
function basicBox4(ticker) {
  $("#box4_content1").show();
  $("#box4_content2").hide();
  $("#box4_content3").hide();
  $("#box4_content4").hide();
  $("#box4_content1").html("<img src='images/preloader.gif' class='ajax_preloader' alt='' />");
  $.get(urlRoot+"index.php?page=stockView1Box4Content&content=generalData&ticker="+ticker, function(data){
    $("#box4_content1").html(data);
    $("#box4_content1 dt").click(function() {
      if ( $("#"+$(this).attr("id")+"_popup").is(":visible") ) { $("#"+$(this).attr("id")+"_popup").remove(); }
      else { calcdatabox_popup ( $(this).attr("id") ); }
    });
  });
}

function fundamentBox4(ticker) {
  $("#box4_content1").hide();
  $("#box4_content2").show();
  $("#box4_content3").hide();
  $("#box4_content4").hide();
  $("#box4_content2").html("<img src='images/preloader.gif' class='ajax_preloader' alt='' />");
  $.get(urlRoot+"index.php?page=stockView1Box4Content&content=fundamental&ticker="+ticker, function(data){
    $("#box4_content2").html(data);
    $("#box4 th").click(function() {
      if ( $("#"+$(this).attr("id")+"_popup").is(":visible") ) { $("#"+$(this).attr("id")+"_popup").remove(); }
      else { calcdatabox_popup ( $(this).attr("id") ); }
    });
  });
}

function tehnicalBox3(ticker) {
  $("#box4_content1").hide();
  $("#box4_content2").hide();
  $("#box4_content3").show();
  $("#box4_content4").hide();
  $("#box4_content3").html("<img src='images/preloader.gif' class='ajax_preloader' alt='' />");
  $.get(urlRoot+"index.php?page=stockView1Box4Content&content=technical&ticker="+ticker, function(data){
    $("#box4_content3").html(data);
    calcdatabox_content3("#box4_content3");
  });
}

function analBox3(ticker) {
  $("#box4_content1").hide();
  $("#box4_content2").hide();
  $("#box4_content3").hide();
  $("#box4_content4").show();
  $("#box4_content4").html("<img src='images/preloader.gif' class='ajax_preloader' alt='' />");
  $.get(urlRoot+"index.php?page=stockView1Box4Content&content=investa&ticker="+ticker, function(data){
    $("#box4_content4").html(data);
    $("#analy_bar_wrapper span").click(function() {
      if ( $("#"+$(this).attr("id")+"_popup").is(":visible") ) { $("#"+$(this).attr("id")+"_popup").remove(); }
      else { calcdatabox_popup ( $(this).attr("id") ); }
    });
  });
}

$(document).ready(function() {
	$("#box4 .boxnav li").click(function() {
		if ( $(this).is(".on") ) {
				return false;
		} else {
      $("#box4 .boxnav li").removeClass('on');
      $(this).addClass('on');
      if ( $("#box4_content1").contents("span").is(".noneSelected") ) { return false; }
        if ( $(this).is("#box4_link1") ) {
          $("#box4_content1").show();
          $("#box4_content2").hide();
          $("#box4_content3").hide();
          $("#box4_content4").hide();
          if ( $("#box4_content1").html() == false ) { basicBox4( $("#box2 .active").children(".name").children("span").text() ); }
        } if ( $(this).is("#box4_link2") ) {
          $("#box4_content1").hide();
          $("#box4_content2").show();
          $("#box4_content3").hide();
          $("#box4_content4").hide();
          if ( $("#box4_content2").html() == false ) { fundamentBox4( $("#box2 .active").children(".name").children("span").text() ); }
        } if ( $(this).is("#box4_link3") ) {
          $("#box4_content1").hide();
          $("#box4_content2").hide();
          $("#box4_content3").show();
          $("#box4_content4").hide();
          if ( $("#box4_content3").html() == false ) { tehnicalBox3( $("#box2 .active").children(".name").children("span").text() ); }
        } if ( $(this).is("#box4_link4") ) {
          $("#box4_content1").hide();
          $("#box4_content2").hide();
          $("#box4_content3").hide();
          $("#box4_content4").show();
          if ( $("#box4_content4").html() == false ) { analBox3( $("#box2 .active").children(".name").children("span").text() ); }
        }
      }
	});
});

//BOX 5 + ACCORDION
$(document).ready(function(){
  if ( $("#box5_content2").children(".inner").children(".scrollbox").children("div").height() > 510 ) { $("#box5_content2").children(".inner").children(".scrollbox").css("overflow", "auto"); }
  $("#box5 span.heading").click(function(){ $("#box5_content2 .scrollbox").css("overflow", "hidden"); });
  $("#box5").accordion({
      active: '.selected',
	    selectedClass: 'selected',
	    header: "span.heading",
	    autoheight: false
	}).bind("change.ui-accordion", function(event, ui) {
      if ( ui.newContent.children(".inner").children(".scrollbox").children("div").height() > 510 ) { ui.newContent.children(".inner").children(".scrollbox").css("overflow", "auto"); }      
  });

	$("#box5_content1_stats").click(function() {
	    if  ($("#box5_content1_stats_popup").is(":visible") || $(this).is(".off") ) {
	        return false;
		} else {
		    $("#box5_popup_form").remove();
		    var pos = $(this).position();
		    $.get(urlRoot+"index.php?page=portfolioStocksStats", function(data){
    				$("body").append(data);
            var top = pos.top - $("#box5_content1_stats_popup").height();
    				var left = pos.left + 160;
    				$("#box5_content1_stats_popup").css("top",top+"px").css("left",left+"px");
    				$("#box5_content1_stats_popup").show();
            $("#close_box5_stats").click(function() {
                $("#box5_content1_stats_popup").remove();
            });
			});
		}

	});

	$("#box5_content1_new").click(function() {
	  if  ( $("#box5_popup_form").is(":visible") || $(this).is(".off") ) { return false; }
	  $("#box5_content1_stats_popup").remove();
    var pos = $(this).position();
    $.get(urlRoot+"index.php?page=portfolioStocksPopUp", function(data){
        $("body").append(data);
        var top = pos.top - $("#box5_popup_form").height();
        var left = pos.left + 160;
        $("#box5_popup_form").css("top",top+"px").css("left",left+"px").show();
        $("#box5_popup_form input[type=radio]").checkbox();
        clearInputs("#box5_popup2_name");
        clearInputs("#box5_popup2_date");
        clearInputs("#box5_popup2_value");
        clearInputs("#box5_popup2_amount");
        clearInputs("#box5_popup2_price");
        $("#box5_popup2_name").autocomplete(urlRoot+"index.php?page=autocomplete");
        $("#box5_popup2_date").datepicker();
        
        /* insert stock to portfolio */
        $("#box5_popup_form .button").click(function(){
            var element = $(this);
            var user_id = $("#box5_popup_form").attr("rel");           
            var ticker = $("#box5_popup2_name").val();
            var date = $("#box5_popup2_date").val();
            var inv_sum = $("#box5_popup2_value").val();
            var num = $("#box5_popup2_amount").val();
            var value = $("#box5_popup2_price").val();
            var cal_type = "";
            if( $("#box5_popup2_calculate_val1").is(":checked") ) {            
              cal_type = "close";
            } if ( $("#box5_popup2_calculate_val2").is(":checked") ) {
              cal_type = "";
            }
            if (inv_sum=="unesi vrijednost investicije") { inv_sum=""; }
            if (num=="Broj kupljenih dionica") { num=""; }
            if (value=="Cijenu dionice") { value=""; }
            
            if (ticker=="" || ticker=="unesi naziv ili oznaku dionice") { return false; }
            if (date=="" || date=="unesi datum") { return false; }
            if (inv_sum=="" && num=="" && value==""){ return false; }
            if (inv_sum==""){
                if (num=="" || value==""){ return false; }
            }
            var dateTemp = date;
            var dateTemp = date.split(".");
            var dateFormat = new Array();            
            dateFormat[0] = dateTemp[2];
            dateFormat[1] = dateTemp[1];
            dateFormat[2] = dateTemp[0];
            $.get(urlRoot+"index.php?page=portfolioStocksInsert&user_id="+user_id+"&ticker="+ticker+"&date="+dateFormat.join('-')+"&inv_sum="+inv_sum+"&num="+num+"&value="+value+"&cal_type="+cal_type, function(data){
                if(data==""){ return false; }
                if ( element.prev().is(".note") ) {   
                } else {
                    element.before('<span class="note"><em>Investicija je unešena</em>Unesite novu investiciju ili zatvorite prozor</span>');                 
                }
                if($("#box5_content1 .text").is(".on")){
                    $("#box5_content1 .text").removeClass("on");
                    $("#box5_content1 .wrap").addClass("on");
                    $("#box5_content1_stats").removeClass("off");
                }
                var dataSplit = data.split("|");
                
                var value = parseFloat(dataSplit[2].replace(/\./g,"").replace(/\,/g,".").replace(/\ /g,""))+parseFloat(dataSplit[3].replace(/\./g,"").replace(/\,/g,".").replace(/\ /g,""));
                var sum1 = parseFloat($("#box5_content1 .result .colhead2").text().replace(/\./g,"").replace(/\,/g,".").replace(/\ /g,""))+value;
                var sum2 = parseFloat($("#box5_content1 .result .colhead3").text().replace(/\./g,"").replace(/\,/g,".").replace(/\ /g,""))+parseFloat(dataSplit[3].replace(/\./g,"").replace(/\,/g,".").replace(/\ /g,""));
                var sum2color;
                
                if(sum2>0){ var sum2color="up"; }
                else { var sum2color="down"; }
                
                $("#box5_content1 .result .colhead2").text(addCommas(sum1.toFixed(2)));
                $("#box5_content1 .result .colhead3").text(addCommas(sum2.toFixed(2))).removeClass("up").removeClass("down").addClass(sum2color);
                
                if(parseFloat(dataSplit[3])>0){ var el2color="up"; }
                else { var el2color="down"; }

                $("#box5 .scrollbox tbody").append('<tr rel="'+dataSplit[5]+'"><td class="col1"><img src="'+urlRoot+'images/ICONclose.gif" alt="zatvori" /></td><td class="col2">'+dataSplit[0].toUpperCase()+'<br /><span>'+dataSplit[1]+'</span></td><td class="col3">'+addCommas(value.toFixed(2))+'</td><td class="col4 '+el2color+'">'+dataSplit[3]+'</td></tr>')
                delStocksFromPortfolio();
            });
        });
        $("#box5_popup_form .close").click(function() {
      	    $("#box5_popup_form").remove();
      	});
    });
	});
	delStocksFromPortfolio();
});

function addCommas(nStr){
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? ',' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + '.' + '$2');
	}

	return x1 + x2;
}

/* delete stock from portfolio */
function delStocksFromPortfolio(){
  $("#box5_content1 .col1 img").unbind("click");
  $("#box5_content1 .col1 img").click(function(){
      var activeRow = $(this).parents("td").parents("tr");
      var usp_id = activeRow.attr("rel");
      $.get(urlRoot+"index.php?page=portfolioStocksDelete&usp_id="+usp_id, function(data){
          if (data!="1") { return false; }
          if($("#box5_content1 .scrollbox tbody tr").length == "1"){
              $("#box5_content1 .result .colhead2").text("0").removeClass("up").removeClass("down");
              $("#box5_content1 .result .colhead3").text("0").removeClass("up").removeClass("down");
              $("#box5_content1 .text").addClass("on");
              $("#box5_content1 .wrap").removeClass("on");
              $("#box5_content1_stats").addClass("off");
              activeRow.remove();
              return false;
          }
          var sum1 = parseFloat($("#box5_content1 .result .colhead2").text().replace(/\./g,"").replace(/\,/g,".").replace(/\ /g,""))-parseFloat(activeRow.children(".col3").text().replace(/\./g,"").replace(/\,/g,".").replace(/\ /g,""));
          var sum2 = parseFloat($("#box5_content1 .result .colhead3").text().replace(/\./g,"").replace(/\,/g,".").replace(/\ /g,""))-parseFloat(activeRow.children(".col4").text().replace(/\./g,"").replace(/\,/g,".").replace(/\ /g,""));
          var sum2color;                
          if(sum2>0){ var sum2color="up"; }
          else { var sum2color="down"; }
          $("#box5_content1 .result .colhead2").text(addCommas(sum1.toFixed(2)));
          $("#box5_content1 .result .colhead3").text(addCommas(sum2.toFixed(2))).removeClass("up").removeClass("down").addClass(sum2color);         
          activeRow.remove();
      });
  });
}

//BOX 6

$(document).ready(function(){
	$("#ex_stck_drop2").focus(function () {
         if ( $("#ex_stck_drop2").attr("value") == "unesite naziv ili oznaku" ) {
            $("#ex_stck_drop2").attr("value","");
		} else {
			return false;
		}
    });
	$("#ex_stck_drop2").blur(function () {
         if ( $("#ex_stck_drop2").attr("value") == "" ) {
            $("#ex_stck_drop2").attr("value","unesite naziv ili oznaku");
		} else {
			return false;
		}
    });
});

//BOX 6 KORACI ZA ANALIZU
function showbox6transfer(box) {
    var height = $(box).height();
  	$(box).hide();
  	$("#box6 .transfer").css("height",height).show().html("<img src='images/preloader.gif' class='ajax_preloader' alt='' />");
}
function showbox6step(box,data) {
    $(box).html(data);
  	var height = $(box).height();
  	$("#box6 .transfer").animate({ height: height}, 750, function() {
  		$(this).hide();
  		$(box).show();
  	});
}
function showbox6back(prevBox,currBox) {
  showbox6transfer (currBox);
	var height = $(prevBox).height();
	$("#box6 .transfer").animate({ height: height}, 750, function() {
		$(this).hide();
		$(prevBox).show();
	});
}
function stop6Analysis(currBox) {
	$("#box6 .box6_anl_stop").click(function() {
        showbox6back("#box6 .step1",currBox);
	});
}
function find6more() {
    $("#box6 .find_more").unbind();
	$("#box6 .find_more").click(function() {
		$pageDimensions=pageDimensions();
		$("body").append("<div id='box6_find_bkg'></div><div id='box6_find' style='display: none;'></div>");
		$("#box6_find_bkg").css({ height:$pageDimensions[0], width:$pageDimensions[1] })
		$(window).resize(function(){
		  $pageDimensions=pageDimensions();
		  $("#box6_find_bkg").css({ height:$pageDimensions[0], width:$pageDimensions[1] })
		});
		$.get(urlRoot+"index.php?page=stockView1Box6PopUp", function(data){
		    $("#box6_find").append(data);	    
		    var top = (($(window).height() - $("#box6_find").height())/2)+$(window).scrollTop();
			var left = ($(window).width() - $("#box6_find").width())/2;
			$("#box6_find").css("top",top).css("left",left).show();
			
			if (navigator.userAgent.toLowerCase().indexOf('msie 6')!=-1){ $("#box6_find .switch>div.on img[@src$=png]").pngfix(); }		
			$("#close_box6_find").click(function() {
			    $("#box6_find_bkg").remove();
			    $("#box6_find").remove();
            });
            $("#box6_find_prev").click(function() {
                $("#box6_find_next").removeClass("off");
                if ( $("#box6_find .switch>div.on").prevAll().length > 0 ) {
				    if ( $("#box6_find .switch>div.on").prevAll().length == 1 ) { $("#box6_find_prev").addClass("off"); }
					$("#box6_find .switch>div.on").removeClass("on").prev().addClass("on");
				} else  { return; }
			});
			$("#box6_find_next").click(function() {
			    $("#box6_find_prev").removeClass("off");
				if ( $("#box6_find .switch>div.on").prevAll().length < ($("#box6_find .switch>div").length -1) ) {
				    if ( $("#box6_find .switch>div.on").prevAll().length == ($("#box6_find .switch>div").length -2) ) { $("#box6_find_next").addClass("off"); }
					$("#box6_find .switch>div.on").removeClass("on").next().addClass("on");
              if (navigator.userAgent.toLowerCase().indexOf('msie 6')!=-1){ $("#box6_find .switch>div.on img[@src$=png]").pngfix(); }
				} else  { return; }
			});
		});
	});
}

function switchBox6Step(step,nextStep,ticker){
    showbox6transfer ("#box6 ."+step);
    $.get(urlRoot+"index.php?page=stockView1Box6Content&step="+nextStep+"&ticker="+ticker, function(data){
        showbox6step("#box6 .step"+nextStep,data);
        stop6Analysis("#box6 .step"+nextStep);
        find6more();
        if(nextStep=="7"){
            for(i=0; i<$("#box6 .step7 table tr").length; i++){
                $("#box6 .step7 table tr:eq("+i+") td:eq(0)").click(function() { 
                    $("#box6 .step7switchBox").hide();
                    $("#step7switchBox"+$(this).attr("rel")).show();
                });
            }
        }
        $("#box6 .step"+nextStep+" .back").click(function() { showbox6back("#box6 ."+step,"#box6 .step"+nextStep); });
        $("#box6 .step"+nextStep+" .next").click(function() { 
          if($(this).is(".off")){ return false; }
          switchBox6Step("step"+nextStep, $(this).attr("id").substr(4),ticker ); 
        });
    });
}
function initSwitchBox6(ticker){
    $("#box6 .step1").hide();
  	$("#box6 .step2").show();
  	
  	var pos = $("#box6").position();
    $("html,body").animate({scrollTop: pos.top}, 1000);
  	
  	
    $("#box6 .step2 .back").click(function() { showbox6back("#box6 .step1","#box6 .step2"); });
    $("#box6 .step2 .next").click(function() { 
      if($(this).is(".off")){ return false; }
      switchBox6Step("step2", $(this).attr("id").substr(4),ticker ); 
    });
}

$(document).ready(function() {
    $("#box6 .ex_stock #ex_stck_drop2").autocomplete(urlRoot+"index.php?page=autocomplete&box=1");
    jQuery("#box6 .ex_stock #ex_stck_drop2").result(function(event, data, formatted) { 
        var ticker = $('#box6 .ex_stock #ex_stck_drop2').attr('value');
        switchBox6Step("step1","2",ticker);
    });
});

//SKRIPTA ZA LOADANJE BOXA 7
$(document).ready(function() {
	function filterNewsBox7(cont) {
	   $("#box7_content"+cont+" input").keydown(function(){
	     $("#box7 form span").css("display","block");
	   });
    $("#box7_content"+cont+" input").keyup(function(){
      var filterVal = $(this).attr('value');
      if (filterVal=="") {
        $("#box7_content"+cont+" h2").css("display","none");
        $("#box7_content"+cont+" .filterAmount").html( $("#box7_content"+cont+" li:visible").length );
        $("#box7_content"+cont+" li").css("display","block");
        $("#box7 form span").css("display","none");
        return false;
      }
       var term = new RegExp( filterVal, 'igm' );
      /*if( filterVal.length > $("#box7_content"+cont+" .filterValue").html().length ){
          $("#box7_content"+cont+" li:visible").each(function(){
            $(this).css("display",(term.test($(this).text()))?"block":"none");
          });
      } else {*/
        $("#box7_content"+cont+" li").each(function(){
            $(this).css("display",(term.test($(this).text()))?"block":"none");
        });
      //}     
      $("#box7_content"+cont+" h2").css("display","block");
      $("#box7_content"+cont+" .filterAmount").html( $("#box7_content"+cont+" li:visible").length );
      $("#box7_content"+cont+" .filterValue").html( filterVal );
      $("#box7 form span").css("display","none");
    });
  }

	news1popup("box7_content1");
	filterNewsBox7("1");
	clearInputs("#box7_content1 input");
	$("#box7 .boxnav li").click(function() {
		if ( $(this).is(".on") ) {
				return false;
			} if ( $(this).is("#box7_link1") ) {
			    $("#box7 .boxnav li").removeClass('on');
			    $(this).addClass('on');
			    $("#box7_content2").hide();
				$("#box7_content3").hide();
				$("#box7_content1").show();
			} if ( $(this).is("#box7_link2") ) {
			    $("#box7 .boxnav li").removeClass('on');
			    $(this).addClass('on');
			    $("#box7_content1").hide();
				$("#box7_content3").hide();
				$("#box7_content2").show();
				if ( $("#box7_content2").html() == false ) {
			        $("#box7_content2").html("<img src='images/preloader.gif' class='ajax_preloader' alt='' />");
					$.get(urlRoot+"index.php?page=stockView1Box7Content&content=2", function(data){
						$("#box7_content2").html(data);
						clearInputs("#box7_content2 input");
						news1popup("box7_content2");
						filterNewsBox7("2");
					});
			    }
			} if ( $(this).is("#box7_link3") ) {
			    $("#box7 .boxnav li").removeClass('on');
			    $(this).addClass('on');
       			$("#box7_content1").hide();
				$("#box7_content2").hide();
				$("#box7_content3").show();
				if ( $("#box7_content3").html() == false ) {
			        $("#box7_content3").html("<img src='images/preloader.gif' class='ajax_preloader' alt='' />");
					$.get(urlRoot+"index.php?page=stockView1Box7Content&content=3", function(data){
						$("#box7_content3").html(data);
						clearInputs("#box7_content3 input");
						news1popup("box7_content3");
						filterNewsBox7("3");
					});
			    }
			}
	});
});
